Can't load image taken from camera into an ImageView - android

I am able to save the image taken from camera into internal storage, however I can't load it into ImageView, which remains empty. I've read all relevant suggestions but couldn't find a suitable solution. Please find relevant code below, any help will be MUCH appreciated, as I'm struggling with it for days...
Manifest permissions:
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
ImageView on XML:
<ImageView
android:id="#+id/recipeImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:background="#color/backgroundColorHomeBottomLayout"
android:padding="30dp" />
Relevant activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
setPic();
//mImageView.setImageURI(fileUri);
}
else if (resultCode == RESULT_CANCELED) {
/** user cancelled Image capture */
Toast.makeText(this,
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
/** failed to capture image */
Toast.makeText(this,
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
/** Internal memory methods */
private void launchCameraIntent() {
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 */
File 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) {
Uri photoURI = FileProvider.getUriForFile(this,
"v3.com.mycookbook5.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
/** return a unique file name for a new photo using a date-time stamp */
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 = "file:" + image.getAbsolutePath();
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}
Log:
07-03 12:56:07.188 3950-16091/? E/Drive.UninstallOperation: Package still installed v3.com.mycookbook5
07-03 12:56:35.350 19680-19680/v3.com.mycookbook5 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Android/data/v3.com.mycookbook5/files/Pictures/JPEG_20160703_125629_-664091716.jpg: open failed: ENOENT (No such file or directory)
07-03 12:56:35.350 19680-19680/v3.com.mycookbook5 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Android/data/v3.com.mycookbook5/files/Pictures/JPEG_20160703_125629_-664091716.jpg: open failed: ENOENT (No such file or directory)

I believe that your problem is because you are not giving the image the required time to be saved to the sdcard as the code starts looking for it before it even completely saved, so you have to provide a delayed handler in order to making sure the image is successfully saved, also use the following way to get the image path:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setPic();
}
}, 750);
and for getting the image from the sdcard:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image_name.jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{
/*
* here you set all of your bmOptions specs
*/
return BitmapFactory.decodeFile(path, bmOptions);
}

Problem solved. To help others, here is how it should be performed:
Downgrade targetSdkVersion on build.gradle from 23 --> 22, to avoid permission issues.
Add the following code to launchCameraIntent() method:
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
Change setPic method as follow:
Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getPath());
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(rotatedBitmap, 200, 150 ,false);
mImageView.setImageBitmap(scaledBitmap);

I would say you might get a zero size image due to trying to resize it to the imageView size (which, if not rendered yet - may be zero size).
Try to load the image without any manipulation and after succeeding - change your code to reduce the memory consumption , but by but until you get the optimal result.
Good luck.

You realize you will have to pull the extra data from the intent right? 'onActivityResult' will get back to your activity with a result code and WITH EXTRA DATA which is the bitmap of the image, you should pass that data (in whatever way you choose) to your setPic method.
To get the Bitmap photo you can use the code down below
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
}

try this code for marshmallow
Uri imageFileUri = data.getData();
final Bitmap bitmap = getBitmapFromUri(imageFileUri);
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getLocalContext().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
//mImageView.setImageURI(fileUri);
Uri imageFileUri = data.getData();
final Bitmap bitmap = getBitmapFromUri(imageFileUri);
setPic(bitmap);
}
else if (resultCode == RESULT_CANCELED) {
/** user cancelled Image capture */
Toast.makeText(this,
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
/** failed to capture image */
Toast.makeText(this,
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}

Related

Android capture image from camera as thumbnail but not as it should be

I have some android code which taking photo from camera. But it is taking the picture as thumbnail but I want to take the picture as it is the original size. Here is my code:
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
CommonResources.photoFinishBitmap = thumbnail;
goForEditing();
//ivImage.setImageBitmap(thumbnail);
}
Can you help me how to get the original image instead of the thumbnail.
You will need to provide a file name for the full-sized photo to be saved into. You will also need to get access to file storage if you are running on Android 6.0 or later.
This answer should provide a code example of saving the full-sized image to a file: https://stackoverflow.com/a/20353771/5527154
Here is the documentation from Google: https://developer.android.com/training/camera/photobasics.html#TaskPath
To take a photo, first we need to declare required permissions in AndroidManifest.xml. We need two permissions:
Camera - to open camera app. If attribute required is set to true you will not be able to install this app if you don't have hardware camera.
WRITE_EXTERNAL_STORAGE - This permission is required to create new file, in which captured photo will be saved.
AndroidManifest.xml
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
The main idea in taking full-sized photo from camera is that we need to create new file for photo, before we open camera app and capture photo.
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
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e("DEBUG_TAG", "createFile", ex);
}
// Continue only if the File was successfully created
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", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getAlbumDir();
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;
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ "/dcim/"
+ "MyRecipes");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private void setPic() {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = recipeImage.getWidth();
int targetH = recipeImage.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 2;
if ((targetW > 0) && (targetH > 0)) {
scaleFactor = Math.max(photoW / targetW, photoH / targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Matrix matrix = new Matrix();
matrix.postRotate(getRotation());
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
/* Associate the Bitmap to the ImageView */
recipeImage.setImageBitmap(bitmap);
}
private float getRotation() {
try {
ExifInterface ei = new ExifInterface(mCurrentPhotoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return 90f;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180f;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270f;
default:
return 0f;
}
} catch (Exception e) {
Log.e("Add Recipe", "getRotation", e);
return 0f;
}
}
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);
sendBroadcast(mediaScanIntent);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
handleBigCameraPhoto();
}
}

Null result after taking a photo

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.

Android Camera Example - Not Saving Image

I'm currently trying to implement the Camera within my app to take a full image and save it. I'm following the guide at android.com under the 'Save the Full-Size Photo' section.
The first part of that tutorial worked without a problem, but it seems to simply not save the full image for some reason. When using the setPic function, it will crash as the Bitmap it gets has a size of 0. The addGalleryPic function doesn't seem to add anything to the gallery either.
Thanks for your help!
Manifiest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Activity:
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
Creating the 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 = 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;
}
Opening the Camera intent.
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
File 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) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Overriding the Activity Result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d( "onResult: " + requestCode + " & " + resultCode );
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Logger.d( "Attempting to open: " + mCurrentPhotoPath );
galleryAddPic();
setPic();
}
}
Adding the image to the gallery.
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);
}
And setting the image to the imageView.
private void setPic() {
// Get the dimensions of the View
int targetW = image.getWidth();
int targetH = image.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Both of these values are zero.
Logger.d( "Size: " + photoW + "x" + photoH );
// Determine how much to scale down the image
// **THIS LINE CRASHES - Divide by zero ( size is zero ).**
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
image.setImageBitmap(bitmap);
}
I recommend that you get rid of String mCurrentPhotoPath and replace it with File mCurrentPhoto (or another name as you see fit). This will clear up a few bugs:
mCurrentPhotoPath = "file:" + image.getAbsolutePath(); results in a value that is neither a valid filesystem path nor a valid string representation of a Uri
File f = new File(mCurrentPhotoPath); results in an invalid File, because of the rogue file: you are putting on the filesystem path in the above bullet
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); will not work, because of the rogue file: you are putting on the filesystem path in the first bullet
Most of the time, you are using the File anyway. And then for decodeFile(), just call getAbsolutePath() at that point (BitmapFactory.decodeFile(mCurrentPhoto.getAbsolutePath(), bmOptions)).

Reading Cached Image File in Android and getting Null from BitmapFactory.decode

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.

Android: wrong orientation of files opened with BitmapFactory.decodeFile

Just simple as the title, files opened with BitmapFactory.decodeFile have wrong orientation when it is displayed on the ImageView. The image its captured from the camera and saved on a tmp file so if the device has the bug that returns data.getData() null I have at least a reference to the file.
This just start the camera activity and capture the image file
private void startCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (hasImageCaptureBug()) {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Constants.TMPFILE_PATH)));
} else {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
Uri uri = null;
if (hasImageCaptureBug()) {
File f = new File(Constants.TMPFILE_PATH);
try {
uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), null, null));
} catch (FileNotFoundException e) {
}
} else {
uri = data.getData();
}
imageFilePath = Image.getPath(this, uri);
if (Image.exists(imageFilePath)) {
ImageView image = (ImageView) findViewById(R.id.thumbnail);
int targetW = (int) getResources().getDimension(R.dimen.thumbnail_screen_width);
int degrees = (int) Image.getRotation(this, uri);
Bitmap bmp = Image.resize(imageFilePath, targetW);
bmp = Image.rotate(bmp, degrees);
image.setAdjustViewBounds(true);
image.setImageBitmap(bmp);
}
}
}
}
And this file resizes the image
public class Image {
public static Bitmap resize(String pathName, int targetW) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(pathName, opts);
int photoW = opts.outWidth;
int photoH = opts.outHeight;
int targetH = Math.round((photoH * targetW) / photoW);
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
opts.inJustDecodeBounds = false;
opts.inSampleSize = scaleFactor;
opts.inPurgeable = true;
bmp = BitmapFactory.decodeFile(pathName, opts);
return bmp;
}
}
Tryed to get the ExifOrientation but always its 0 because the file itself its correctly oriented just when I load it the file is displayed with the wrong orientation.
Regards
seems that my issue to preview the image was the Constants.TMPFILE_PATH, the image was not saved there, I just use this fix Display the latest picture taken in the image view layout in android!, but the issue persist if I post it to the server... I'll check this as answered and open a new question to this...
Edited
To solve this issue just refactor the new image and then upload it to the server, because the raw data of the file itself has his exif orientation was wrong.

Categories

Resources