I need to take a photo, get the full-size file to send to a server. With thumbnails it works fine, but with i can't recover the full-size photo. I read and copied most of the code from google tutorial on android developers web page.
I'm doing this:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
mPhotoFile = null;
try {
mPhotoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (mPhotoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mCurrentPhotoPath);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File storageDir;
if (StorageUtils.isExternalStorageWritable()) {
storageDir = StorageUtils.getExternalStorageAppDir(getActivity());
} else {
storageDir = Environment.getDataDirectory();
}
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
Bitmap bitmap= BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); // returns null
mImageAdapter.addImage(bitmap);
}
}
This line (inside onActivityResult returns null):
Bitmap bitmap= BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
I read a lot of posts about camera issues but nothing seems to work. I'm doing something wrong?
Thanks in advance.
Note: i test the code in an emulator and in a real device. Same result.
The problem was in this line:
bmOptions.inJustDecodeBounds = true;
The google doc about bmOptions.inJustDecodeBounds says:
If set to true, the decoder will return null (no bitmap), but the
out... fields will still be set, allowing the caller to query the
bitmap without having to allocate the memory for its pixels.
After removing this line the image was returned ok.
Related
Using this to open camera:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
and in OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK)
{
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
if (data != null) {
cameraBitMap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
cameraBitMap.compress(Bitmap.CompressFormat.JPEG,100, bytes);
cameraFilePath = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
cameraFilePath.createNewFile();
fo = new FileOutputStream(cameraFilePath);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraFilePath.getAbsolutePath(), options);
imageHeight = options.outHeight;
imageWidth = options.outWidth;
camImagePath = String.valueOf(cameraFilePath);
String fileName = camImagePath.substring(camImagePath.lastIndexOf("/") + 1);
txt_FileName.setText(fileName);
txt_FileName.setVisibility(View.VISIBLE);
btn_ImageTest.setImageBitmap(cameraBitMap);
}
}
I want the original size image to display when I capture it from the camera.
Use Intent like this. Here first give image name .
//declare globally
private static final int CAMERA_CODE = 101 ;
private Uri mImageCaptureUri;
Start Intent as below.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
if (f.exists()) {
f.delete();
}
mImageCaptureUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(intent, CAMERA_CODE);
And in onActivityResult :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
System.out.println("Camera Image URI : " + mImageCaptureUri);
String path = mImageCaptureUri.getPath();
if (new File(path).exists()) {
Toast.makeText(MainActivity.this, "Path is Exists..", Toast.LENGTH_LONG).show();
}
btn_ImageTest.setImageURI(mImageCaptureUri);
}
}
You need to create temporary file before you start Camera Activity Intent.
Anything that using below code or similar like that after you take image using camera actually is a thumbnail image which is reduced the original quality.
This is the code that I meant:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
Refer Here for more info
This are the solution that you want
First You need to create temporary file.
Convert the temporary file into URI
Pass URI data to Camera intent by using putExtra method.
Open Camera Activity intent.
Handle onActivityResult if user cancel or accept the image from Camera Activity intent.
Below are the method you can use for step by step mentioned above.
Create Temporary File.
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Convert Temporary file to URI and invoke camera activity intent.
static final int REQUEST_TAKE_PHOTO = 1;
Uri photoURI;
File photoFile;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Now you already have File location path created before Camera Activity intent called. You can handle RESULT_OK(Show image) or RESULT_CANCELED(Delete temporary image).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
mImageView.setImageURI(photoURI );
}else{
photoFile.delete();
}
}
*Take note on getUriForFile which returns a content:// URI. For more recent apps targeting Android 7.0 (API level 24) and higher, passing a file:// URI across a package boundary causes a FileUriExposedException. Therefore, we now present a more generic way of storing images using a FileProvider.
Full documentation is here for reference.
Taking Photo Simply
I want to get image from camera, using
public void LicenseCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, PROFILE_REQUEST_CAMERA);
}
Return bitmap, but it works perfectly. Unfortunately image show as a really small size.
So, i have to keep searching until i get
public void licenseCameraIntent() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri mImageCaptureUri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri1);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, LICENSE_REQUEST_CAMERA);
}
On OnActivityResult data always show null result. How I can fix this issue. It is possible using first solution but return bigger image?
Thanks
while you are capture image from the camera you have created a file for an image that is your image full path so make it globally.
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
and the image file, mCurrentPhotoPath is the full path of image
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
after onActivityResult() you get the image from mCurrentPhotoPath
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For more info, you can check this link Capture Image from Camera and Display in Activity
try this,
public static int REQUEST_CAMERA = 111;
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
code for onStartActivityForResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
_FileName = "image file";
capturePic = null;
file_pdf = null;
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//mImageView.setImageBitmap(imageBitmap);
img_ticket_detail.setImageBitmap(imageBitmap);
capturePic = imageBitmap;
}
}
}
also you can use glide library for show image
I have a problem, that when i have taken an image from camera, image not displaying in imageview.
I created the code by referring the following link
http://developer.android.com/training/camera/photobasics.html
I am posting my code, please have a look,
public void takeImage(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "sample_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
galleryAddPic();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
The image captured is storing in SDcard. But not showing in imageview.
Where i have gone wrong. I have tried a lot. But no result. Is there any way to solve this issue.
this works for me:
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
image.setImageBitmap(myBitmap);
You don't need to create the temp file, just put the Uri in the intent. After the capture, check the file existence of that Uri. If it exists, capture has been done successfully.
I take a photo and save result in a file. The resulting photo exists, I can open it with file manager. However, I cannot convert that file into a valid Bitmap. I've tried different ways, including BitmapFactory, but it always returns a null Bitmap.
Resulting URI, i.e. mImageUri, is
file:///storage/emulated/0/Pictures/IMG_20150126_180346_1663372760.jpg
and path
/storage/emulated/0/Pictures/IMG_20150126_180346_1663372760.jpg
Code is below.
Utils class to create new image file
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
Creating mImageUri in onCreate()
try {
mPhotoFile = Utils.createImageFile();
mImageUri = Uri.fromFile(mPhotoFile);
} catch (IOException ex) {
Toast.makeText(this, getString(R.string.error_something_wrong_happened), Toast.LENGTH_LONG).show();
}
Invoking Camera Intent
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null && mImageUri != null) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(takePhotoIntent, REQUEST_CAMERA);
}
Parsing results
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
//Unable to get Bitmap from mImageUri
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
Log.d(TAG, "bitmap exists " + bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android version is 4.4.4
Maybe is late but I fixed my issue with "bitmap=BitmapFactory.decodeFile(uri);"
The crazy thing is that I didn't need to put "file://" bcos BitmapFactory accept straight way "/storage/emulated/......../bla.jpeg"
Before I was trying to use:
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(uri));
But didn't works....
I am trying to get an image taken from the camera, and storing it locally in a cache to preview in an ImageView and upload to a server when needed. The bitmap that I get back is null.
Below is my code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE){
if (resultCode == RESULT_OK){
// TODO - save the full sized image as well
if(mCurrentPhotoPath!=null){
Log.i(TAG, "Image File found!");
Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
if (imageBitmap !=null){
Log.i(TAG, "Successfully retrieved image back.");
}
ImageView postImageView= (ImageView) getActivity().findViewById(R.id.post_image);
postImageView.setImageBitmap(imageBitmap);
}
}
}
}
String mCurrentPhotoPath;
private File createImageCache(Context context) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getCacheDir();
Log.i(TAG, "StorageDir: "+storageDir);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Searching around one of the solutions that I found and tried was setting the BitmapFactory.Options, but it didn't work for my case.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Edit: Ran getActivity().getCacheDir().list() and found that the files are indeed saved. Also, here is the button that saves the images:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getActivity().getPackageManager())!=null){
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageCache(getActivity());
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "Error Creating File!!! No Space??");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}else{
Toast.makeText(getActivity(),"Please check your camera", Toast.LENGTH_SHORT).show();
Log.i(TAG, "No camera to run");
}
}
});
and found that the files are indeed saved. Just a list() will not prove that. You created the files yourself so they were there already with length 0. What is the length in bytes afterwards? I think still 0. getCacheDir() delivers internal private memory unreachable for the external picture taker. Try with getExternalCacheDir() instead.