How to use default camera to take a picture in android ?
Uri imageUri;
final int TAKE_PICTURE = 115;
public void capturePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photoFile = new File(Environment.getExternalStorageDirectory(), "Photo.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
imageUri = Uri.fromFile(photoFile);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = imageUri;
//Do what ever you want
}
}
}
The intent which is used to open the camera is
buttonCapturePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
The code which gives you the image after capturing is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriImage;
InputStream inputStream = null;
if ( (requestCode == SELECT_IMAGE || requestCode == CAPTURE_IMAGE) && resultCode == Activity.RESULT_OK) {
uriImage = data.getData();
try {
inputStream = getContentResolver().openInputStream(uriImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
imageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
}
}
This is a simple example.Anyway this will return the image as a small bitmap.If you want to retrive the full-sized image ,is a bit more complicated.
ImageView takePhotoView = (ImageView) findViewById(R.id.iwTakePicture);
Bitmap imageBitmap = null;
takePhotoView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
dispatchTakePictureIntent(0);
}
});
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
this.imageBitmap = (Bitmap) extras.get("data");
takePhotoView.setImageBitmap(imageBitmap);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK)
handleSmallCameraPhoto(data);
}
Related
i am trying to get the uri of the picture that have been taken from device camera. I just tried some of the advices from online but i could not manage to solve this problem here is the my code parts.
ImageView petImage;
Uri imageData;
petImage = view.findViewById(R.id.imgPetPic);
petImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// display error state to the user
Toast.makeText(getActivity(), "Camera is Not Available", Toast.LENGTH_SHORT).show();
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
imageData = data.getData();
Bitmap bp = (Bitmap) data.getExtras().get("data");
petImage.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED)
Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
}
}
After that code parts worked. ımageData variable is still null. How do i fix this.
I have added Camera permissions as well which is working perfectly but the image view is not holding the image that is captured. The manifest file is also proper still. The app isn't crashing even it is not showing any errors as well. And I even want to add the image to the database.
public class RiderProfile extends AppCompatActivity {
ImageView imgDp,imgDlFront,imgDlback;
TextView txtDp,txtDl;
Button btnSave;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "1111";
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rider_profile);
imgDp = (ImageView)findViewById(R.id.imgDp);
imgDlFront = (ImageView)findViewById(R.id.imgDlFront);
imgDlback = (ImageView)findViewById(R.id.imgDlback);
txtDp = (TextView) findViewById(R.id.txtDp);
txtDl = (TextView)findViewById(R.id.txtDl);
btnSave = (Button) findViewById(R.id.btnSave);
imgDp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo1 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDp.setImageBitmap(photo1);
}
}
});
imgDlFront.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo2 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlFront.setImageBitmap(photo2);
}
}
});
imgDlback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo3 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlback.setImageBitmap(photo3);
}
}
});
}
}
1. #Override
public void onCameraOpen() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
try {
imageFile = CameraUtils.createImageFile(this);
} catch (IOException e) {
e.printStackTrace();
return;
}
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", imageFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(pictureIntent, IntentRequestCode.RESULT_CODE_IMAGE_CAPTURE);
}
}
2. #Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_CODE_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
onCaptureImage(imageFile, imageUri);
} else {
Toast.makeText(this, "Camera canceled", Toast.LENGTH_SHORT).show();
}
break;
}
}
3. void onCaptureImage(File imageFile, Uri imageUri) {
Uri uri = Uri.fromFile(imageFile);
String selectedImagePath = CameraUtils.getPath(application, uri);
File file1 = new File(selectedImagePath);
if (file1.length() != 0) {
FileAttachments b_data = new FileAttachments();
b_data.setFileName(file1.getName());
CameraUtils.writeScaledDownImage(file1, getApplication());
b_data.setFile(file1);
}
}
I implemented this git on my current project without cloning
implementation 'com.github.adityaarora1:LiveEdgeDetection:master-SNAPSHOT'
But I'm unable to call it on my method. The document says
Start startActivityForResult from your activity
startActivityForResult(new Intent(this, ScanActivity.class), REQUEST_CODE);
Get a file path for cropped image on onActivityResult
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
So I tried calling like this onClick button from a new Class
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
ScanActivity.class);
startActivity(myIntent);
}
and put the rest inside my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
}
Edit: here is the MainActivity the author used on git I tried using it I get this error:
scannedImageView = findViewById(com.adityaarora.liveedgedetection.R.id.scanned_image);
MainActivity (imported)
private static final int REQUEST_CODE = 101;
private ImageView scannedImageView;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannedImageView = findViewById(com.adityaarora.liveedgedetection.R.id.scanned_image);
startScan();
scan = findViewById(R.id.open_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(ScanActivity2.this,
ScanActivity.class);
startActivityForResult(myIntent ,111);
}
});
}
private void startScan() {
Intent intent = new Intent(this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(null != data && null != data.getExtras()) {
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
scannedImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
scannedImageView.setImageBitmap(baseBitmap);
}
} else if(resultCode == Activity.RESULT_CANCELED) {
finish();
}
}
}
Update :
After some research I found that the imported project was on read file only and cannot be changed (ScanActivity.java) and my current project was updated sdk 28 which is different from the one Imported so there is some errors in ScanActivity which Is why the button (technically) wasn't working
You should use startActivityForResult instead of startActivity like below.
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
ScanActivity.class);
startActivityForResult(myIntent ,111);
}
});
and modify your onActivityResult like
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == 111){
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
Log.d("YourTAG","File Path "+filePath);
// here you can set bitmap to your image view
yourImageView.setImageBitmap(baseBitmap);
}
}
UPDATE
You Main Activity should be like
private static final int REQUEST_CODE = 111;
private ImageView scannedImageView;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannedImageView = findViewById(R.id.scanned_image); // this ImageView should be in your activity_scan.xml file with same id(scanned_image)
startScan();
scan = findViewById(R.id.open_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startScan();
}
});
}
private void startScan() {
Intent intent = new Intent(ScanActivity2.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(null != data && null != data.getExtras()) {
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
scannedImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
scannedImageView.setImageBitmap(baseBitmap);
}
} else if(resultCode == Activity.RESULT_CANCELED) {
finish();
}
}
}
Demo project
I have uploaded a demo project on Github which is integrated LiveEdgeDetection library and working as expected.
To check it go here
I have created an activity that upon button click user are able to upload a picture from their device gallery, which would get cast to an imageview. The problem is that it is only able to retrieve image from device gallery, not from phone camera gallery, or from phone google drive folder. I would want that its able to upload any picture from their phone, regardless of the source.
Below is the code:
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
Any help would be greatly appreciated.
Update:
private static final int READ_REQUEST_CODE = 42;
in the code
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
}
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
}
error:
The method parse(String) in the type Uri is not applicable for the arguments (File)
in line
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
Update 2:
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.fromFile(new File("/sdcard/myimage.jpg")));
error:
The method setImageUri(Uri) is undefined for the type ImageView
It would be better to use Intent to search the image type files available in your device.
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE); // set READ_REQUEST_CODE to 42 in your class
Now, process your results in the onActivityResult() method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
i use imageview.onclick for call galley and select picture , frist click image not come to imageview but second click image update i dont know why or have any idea ?
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);
imageView.setImageBitmap(resize);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
resize = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Move imageView.setImageBitmap(resize); to onActivityResult
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
resize = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
imageView.setImageBitmap(resize);
} catch (Exception e) {
e.printStackTrace();
}
}
}