Basically I'm trying to rotate a Bitmap (from an image) in an Android App. The reason why I want to do this is that a picture taken from the camera (through an intent) is displayed horizontally even if it's captured vertically, and the orientation is kept as metadata on the image. Correct me if in wrong. The problem is, however, that the image will take up a lot of memory when loaded in, if taken on a phone with a reasonably good camera, and I haven't found a way to rotate and save it without the risk of getting OutOfMemoryError. The code below is where i:
Load in the image
Check if it needs to be rotated
Loads a scaled-down version for display in an ImageView
Rotates the small image if necessary
In a seperate thread; load, rotate and save the image, so it doesn't need to in the future
It is important for the application to keep the images in the resolution, but any tricks with encodings are welcome. I have searched the internet for a few days, unable to find anything more than what i already have implemented. There is another thread on the subject here, but there doesn't seem to be any solutions. Hope you can help.
public Bitmap getBitmap(final Context c) {
if (bitmap != null)
return bitmap;
final int rotate = necessaryRotation(c, file);
// if(rotate != 0) rotateImageFile(c, rotate);
try {
// Get scaled version
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
options.inSampleSize = calcInSampleSize(options, 1024, 1024);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, options);
// rotate?
bitmap = rotateImage(c,bitmap,rotate);
System.out.println("Bitmap loaded from file: size="
+ bitmap.getWidth() + "," + bitmap.getHeight());
System.gc();
} catch (Exception e) {
System.err.println("Unable to load image file: "
+ this.getFilename());
}
// if rotation is needed, do it in worker thread for next time
if(rotate != 0){
Thread t = new Thread(new Runnable(){
public void run() {
// load entire image
try{
File imageFile = new File(getFilename());
Bitmap huge = Media.getBitmap(c.getContentResolver(),
Uri.fromFile(imageFile));
huge = rotateImage(c,huge,rotate);
// save bitmap properly
FileOutputStream out = new FileOutputStream(imageFile);
huge.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
huge.recycle();
huge = null;
out = null;
System.gc();
}catch(IOException e){
e.printStackTrace();
}
}
});
t.start();
}
return bitmap;
}
private Bitmap rotateImage(Context c, Bitmap bitmap, int rotate) {
if (rotate != 0) {
// rotate
Matrix m = new Matrix();
m.postRotate(rotate);
Bitmap rotImage = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
bitmap.recycle();
System.out.println("Image (id=" + getId()
+ ") rotated successfully");
System.gc();
return rotImage;
}
return bitmap;
}
private int necessaryRotation(Context c, String imageFile) {
int rotate = 0;
ExifInterface exif;
try {
exif = new ExifInterface(imageFile);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rotate;
}
private int calcInSampleSize(BitmapFactory.Options options, int reqWidth,
int reqHeight) {
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
while (height > reqHeight || width > reqWidth) {
height /= 2;
width /= 2;
inSampleSize *= 2;
}
return inSampleSize;
}
If there is anything you need to know or have any optimizations i might be able to use to reduce memory usage, please write :) Thanks
Try this snippet:
private Bitmap rotateImage(Context c, Bitmap bitmap, int rotate) {
....
// reduce byte per pixel
bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
Bitmap.createBitmap(bitmap,...
}
Related
I have created a custom camera. When I click on the capture button in the application, image has been taken. Moreover, I am getting the data in the form of byte array in the function named as onPictureTaken.
I am converting the byte array into the bitmap using the library known as Glide.
My problem is that in Samsung device the images rotates itself. I have been researching on it for quite a while. I found the library called as metadata extraction library to get the Exif information from byte[] and rotate the image on it but it is not working on the Samsung devices. The metadata extraction library every time returns a value of 1 for portrait image which shows that image does not need rotation however, the image taken in portrait mode is always 90 degree rotated.
Whenever, the photo is taken in portrait mode it is rotated at an angle of 90 degrees for both front and back camera and meta extraction library shows a value of 1.
Is there something other then metadata extraction extraction library which extract Exif information stream data?
Note: I cannot use ExifInterface because it requires the minimum Api level of 24 whereas, I am testing on API level 22
I have tried many solution but nothing is working. Is there any solution for this?
The code is given below:
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Glide.with(this).load(data)
.asBitmap().centerCrop().animate(R.anim.abc_fade_in)
.into(new SimpleTarget<Bitmap>(width, height) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
camera_view.setVisibility(View.INVISIBLE);
int w = resource.getWidth();
int h = resource.getHeight();
// Setting post rotate to 90
Matrix mtx = new Matrix();
try {
InputStream is = new ByteArrayInputStream(data);
Metadata metadata = ImageMetadataReader.readMetadata(is);
final ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
if (exifIFD0Directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) {
final int exifOrientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
switch (exifOrientation) {
case 6:
mtx.postRotate(90);
break; // top left
case 3:
mtx.postRotate(180);;
break; // top right
case 8:
mtx.postRotate(270);
break; // bottom right
}
photo = Bitmap.createBitmap(resource, 0, 0, w, h, mtx, true);
/* Work on exifOrientation */
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using Samsung J5 for the testing.
You don't need a library for this. Here is a couple methods that I wrote that should do the trick for you.
public static int getCapturedImageOrientation(Context context, Uri imageUri){
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imageUri.getPath());
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Log.i("RotateImage", "Exif orientation: " + orientation);
Log.i("RotateImage", "Rotate value: " + rotate);
} catch (Exception e) {
Log.e(TAG, "Error getting rotation of image");
}
return rotate;
}
public static int GetRotateAngle(Context context, Uri imageUri) {
String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION };
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (cursor == null) {
//If null, it is not in the gallery, so may be temporary image
return getCapturedImageOrientation(context, imageUri);
}
cursor.moveToFirst();
int orientationColumnIndex = cursor.getColumnIndex(columns[1]);
int orientation = cursor.getInt(orientationColumnIndex);
cursor.close();
return orientation;
}
I wrap these in a class called ImageHelper. You can use it like this:
rotateImage(ImageHelper.GetRotateAngle(Context, mCropImageUri));
Then of course the rotateImage code would be:
private void rotateImage(int degrees) {
Matrix mat = new Matrix();
mat.postRotate(degrees);
mCropImage = Bitmap.createBitmap(mCropImage, 0, 0, mCropImage.getWidth(), mCropImage.getHeight(), mat, true);
setImageForCropping(mCropImage);
}
Of course i was doing all this for a photo editing, cropping and scaling app, so you can ignore some of the extras, but this should take care of ya. Goodluck.
Almost in all Samsung Devices the image rotation Issue is common ,in my case i am using Samsung Note 3 and this same issue occurs but i am using below code to solve this issue
public static Bitmap decodeFile(String path) { // this method is for avoiding the image rotation
int orientation;
try {
if (path == null) {
return null;
}
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 4;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, o2);
Bitmap bitmap = bm;
ExifInterface exif = new ExifInterface(path);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == 3)) {
m.postRotate(180);
m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
return bitmap;
} else if (orientation == 6) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
return bitmap;
} else if (orientation == 8) {
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
return bitmap;
}
return bitmap;
} catch (Exception e) {
}
return null;
}
This code is work for me so i hope this will helpful for you
This can be easily fixed by using ExifInterface provided by Google.
You can add it to your project as follows:
implementation "androidx.exifinterface:exifinterface:1.1.0"
After this, get the rotation from your image and apply it to your ImageView:
// uri of the image
val inputStream = contentResolver.openInputStream(Uri.parse(uri))
val exifInterface = ExifInterface(requireNotNull(inputStream))
var rotation = 0
when (exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotation = 90
ExifInterface.ORIENTATION_ROTATE_180 -> rotation = 180
ExifInterface.ORIENTATION_ROTATE_270 -> rotation = 270
}
In my app, I let the user the chance to get a photo and set it as profile pic. There are 2 ways for getting the photo, from the gallery, and directly taken with the camera.
I have wrote code that works with booth methods, and I have tested on a Galaxy S5 with lollipop 5.0. When testing it with a KitKat 4.4.4, it is throwing a NPE. But is throwing this NPE just when taking the photo directly from the camera.
In booth cases, this is the structure I follow:
Get the Uri from the onActivityResult call data.
Get pic orientation value (in some cases the portrait image appears rotated in the imageview).
Decode the bitmap to downsize it mantaining the aspect ratio.
Rotate the image if it has the wrong orientation.
Save the bitmap in the internal app data.
An this is the code for the "take photo from camera" request:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO_REQUEST_FRAG:
if (resultCode == getActivity().RESULT_OK && data != null) {
Uri selectedImageUri = data.getData();
Bitmap srcBmp = null;
/*Get image orientation*/
int orientation = getImageOrientation(getActivity(), selectedImageUri);
Log.d("IMAGE_ORIENTATION", String.valueOf(orientation));
/*Downsize bitmap mantaining aspect ratio*/
srcBmp = decodeSampledBitmapFromUri(
selectedImageUri,
pic_view.getWidth(), pic_view.getHeight());
/*Rotate image if needed*/
if (orientation == 90) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
srcBmp = Bitmap.createBitmap(srcBmp, 0, 0,
srcBmp.getWidth(), srcBmp.getHeight(), matrix,
true);
}
else if (orientation == 180) {
Matrix matrix = new Matrix();
matrix.postRotate(180);
srcBmp = Bitmap.createBitmap(srcBmp, 0, 0,
srcBmp.getWidth(), srcBmp.getHeight(), matrix,
true);
}
else if (orientation == 270) {
Matrix matrix = new Matrix();
matrix.postRotate(270);
srcBmp = Bitmap.createBitmap(srcBmp, 0, 0,
srcBmp.getWidth(), srcBmp.getHeight(), matrix,
true);
}
/*Save bitmap in internal memory*/
ContextWrapper cw1 = new ContextWrapper(getActivity().getApplicationContext());
File directory1 = cw1.getDir("profile", Context.MODE_PRIVATE);
if (!directory1.exists()) {
directory1.mkdir();
}
File filepath1 = new File(directory1, "profile_pic.png");
FileOutputStream fos1 = null;
try {
fos1 = new FileOutputStream(filepath1);
srcBmp.compress(Bitmap.CompressFormat.JPEG, 90, fos1);
fos1.close();
} catch (Exception e) {
Log.e("SAVE_FULL_IMAGE", e.getMessage(), e);
}
/*Show image in imageview*/
pic_view.setImageBitmap(srcBmp);
}
break;
}
}
-
/*Downsize the bitmap from uri*/
public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) {
Bitmap bm = null;
try{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return bm;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
-
/*Get image orientation first from Exif info*/
public int getImageOrientation(Context context, Uri photoUri) {
int orientation = getOrientationFromExif(photoUri);
if(orientation <= 0) {
orientation = getOrientationFromMediaStore(context, photoUri);
}
return orientation;
}
private int getOrientationFromExif(Uri photoUri) {
int orientation = -1;
try {
ExifInterface exif = new ExifInterface(photoUri.getPath());
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_NORMAL:
orientation = 0;
break;
default:
break;
}
} catch (IOException e) {
Log.e("EXIF_ORIENTATION", "Unable to get image exif orientation", e);
}
return orientation;
}
/* normal landscape: 0
* normal portrait: 90
* upside-down landscape: 180
* upside-down portrait: 270
* image not found: -1
*/
private static int getOrientationFromMediaStore(Context context, Uri photoUri) {
String[] projection = {MediaStore.Images.ImageColumns.ORIENTATION};
Cursor cursor = context.getContentResolver().query(photoUri, projection, null, null, null);
try {
if (cursor.moveToFirst()) {
return cursor.getInt(0);
} else {
return -1;
}
} finally {
cursor.close();
}
}
It is throwing the NPE in the line where I want to get the image orientation from the exif data, exactly where I get the Path from the uri:
ExifInterface exif = new ExifInterface(photoUri.getPath());
So I know that it must be something with the path. I have readed several posts about that kitkat returns the path in a diferent format. I have tried diferent custom getPath() methods, but always throws NPE when calling the Cursor.
So I know that it must be something with the path.
That's because it's not a filesystem path. A Uri is not a file, and while you are handling that properly elsewhere, you are not doing so here.
You need to switch to EXIF logic that can handle an InputStream, such as this code culled from the AOSP Mms app.
I've seen several questions regarding this topic, but none that address my problem.
I dynamically create ImageViews and allow the user to take/add photos of items for an inventory. The following code exists to generate the Bitmap and populate the ImageView:
protected void addPhotosToView(ArrayList<String> uris) {
for (String uriString : uris) {
try {
Uri uri = Uri.parse(uriString);
File imageFile = new File(uri.getPath());
int orientation = resolveBitmapOrientation(imageFile);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
bitmap = applyOrientation(bitmap, orientation);
ImageView image = new ImageView(ItemActivity.this);
int h = 100; // height in pixels
int w = 100; // width in pixels
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, h, w, true);
image.setImageBitmap(scaled);
LinearLayout photoLayout = (LinearLayout) findViewById(R.id.itemPhotoLayout);
photoLayout.addView(image);
addClickListener(image, uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
But once the image is added or taken, some images appear with the wrong orientation. Some of the photos stored in the phone in portrait are displayed in portrait, while others appear to be in landscape. Landscape photos are equally arbitrary.
This does not appear to be happening on all devices (the device that I'm seeing this on is a Samsung S4)
As you can see in the code, I have tried getting/applying orientation changes using Exif tags, but I'm always getting 0 for the orientation with this device and have not seen any answers for questions that ask for a solution when orientation is always 0.
I'm looking to ship this software soon and need some sort of workaround or solution, so I'm willing to accept some other way of going from Uris/strings to a dynamic, horizontally scrollable list of properly oriented images if this can't be resolved any other way.
you need to decode the bitmap that's all try this tutorial you can download the source.
that application dose exactly what you want maybe it will help you i hope because it worked fine with my application
Please use this method to show/decode your bitmap. It is taken from another SO post I cant remember which and is modified for my use. This method returns bitmap according to the exif orientation data if present on the image:
public Bitmap decodeFile(String path) {// you can provide file path here
int orientation;
try {
if (path == null) {
return null;
}
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
// final int REQUIRED_SIZE = 20;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 0;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, o2);
Bitmap bitmap = bm;
ExifInterface exif = new ExifInterface(path);
orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
photo(bitmap, path);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
photo(bitmap, path);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
photo(bitmap, path);
return bitmap;
}
return bitmap;
} catch (Exception e) {
return null;
}
}
I'm trying to take an image captured from the camera and place a photoframe or overlay over it. The photoframe is basically a png image placed in an ImageView within a FrameLayout that also contains the SurfaceView. The problem is that I must scale either or both of the resulting bitmaps of the view containing the photo image and the photo frame image in order for the overlay to be placed in exactly the correct position over the captured photo image. But since they have different aspect ratios, I'm at a loss to figure out how to do this without either the photo or the overlay from getting distorted. Here is my code that handles the bitmap manipulations. In addition, I sometimes get OutofMemory exceptions due to the huge size of the bitmaps. I tried to use MappedByteBufferbut couldn't get that to work right either... sigh. Anyway, any suggestions on what I'm doing wrong or code samples that show a better way to accomplish this are greatly appreciated!
private void saveTempPhoto(byte[] data) {
// Need to flip back the photo frame on front facing camera.
if (this.isCameraFront)
this.flipPhotoFrame();
findViewById(R.id.close_button).setVisibility(View.INVISIBLE);
findViewById(R.id.flash_button).setVisibility(View.INVISIBLE);
findViewById(R.id.focus_button).setVisibility(View.INVISIBLE);
findViewById(R.id.take_photo).setVisibility(View.INVISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[32 * 1024];
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inJustDecodeBounds = true;
Bitmap bitmapPhoto = null;
Bitmap bitmapPhotoFrame = null;
Bitmap bitmapCanvas = null;
View view = findViewById(R.id.top_photo_frame); //view containing the photoframe
try {
int photoFrameWidth = view.getWidth();
int photoFrameHeight = view.getHeight();
BitmapFactory.decodeByteArray(data, 0, data.length, options);
if (orientation == 90 || orientation == 270) {
//Swap height and width
int temp = options.outWidth;
options.outWidth = options.outHeight;
options.outHeight = temp;
}
// Calculate the best sample size to use based on the ratio of the captured image to the photoframe.
// This is done to prevent OutofMemoryExceptions from occurring, as the bitmap allocations can use up a lot of heap space.
float ratioWidth = (float)options.outWidth / (float)photoFrameWidth;
float ratioHeight = (float)options.outHeight / (float)photoFrameHeight;
float ratio = Math.min(ratioWidth, ratioHeight);
if (ratioWidth > 1 || ratioHeight > 1) {
double power = Math.log(ratio) / Math.log(2);
options.inSampleSize = (int) Math.pow(2, Math.round(power));
}
options.inJustDecodeBounds = false;
Bitmap bitmapPhotoPreRotate = BitmapFactory.decodeByteArray(data, 0, data.length, options);
int postRotation = isCameraFront ? -orientation : orientation;
if (orientation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(postRotation);
bitmapPhoto = Bitmap.createBitmap(bitmapPhotoPreRotate, 0, 0, bitmapPhotoPreRotate.getWidth(), bitmapPhotoPreRotate.getHeight(), matrix, true);
bitmapPhotoPreRotate.recycle();
}
else
bitmapPhoto = bitmapPhotoPreRotate;
Log.d("PhotoFrameActivity", String.format("Photo bitmap has width %d and height %d", bitmapPhoto.getWidth(), bitmapPhoto.getHeight()));
Log.d("PhotoFrameActivity", String.format("PhotoFrame bitmap has width %d and height %d", view.getWidth(), view.getHeight()));
int photoWidth = bitmapPhoto.getWidth();
int photoHeight = bitmapPhoto.getHeight();
Bitmap.Config photoConfig = bitmapPhoto.getConfig();
bitmapCanvas = Bitmap.createBitmap(photoWidth,
photoHeight, photoConfig);
if (bitmapCanvas != null) {
Canvas canvas = new Canvas(bitmapCanvas);
canvas.drawBitmap(bitmapPhoto, new Matrix(), null);
bitmapPhoto.recycle();
bitmapPhoto = null;
System.gc(); //Try to force GC here to free up some memory
bitmapPhotoFrame = Bitmap.createScaledBitmap(
this.loadBitmapFromView(view),
photoWidth,
photoHeight,
true);
canvas.drawBitmap(bitmapPhotoFrame, 0, 0, null);
bitmapPhotoFrame.recycle();
Log.d("PhotoFrameActivity", String.format("Combined bitmap has width %d and height %d", bitmapCanvas.getWidth(), bitmapCanvas.getHeight()));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapCanvas.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] jpegWithPhotoFrame = stream.toByteArray();
try {
createPhotoFile();
FileOutputStream fos = new FileOutputStream(photoFile);
fos.write(jpegWithPhotoFrame);
fos.close();
Log.d("PhotoFrameActivity", String.format("Image file saved to %s", photoFile.getPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bitmapCanvas != null)
bitmapCanvas.recycle();
if (bitmapPhoto != null)
bitmapPhoto.recycle();
if (bitmapPhotoFrame != null)
bitmapPhotoFrame.recycle();
}
}
catch (OutOfMemoryError e) {
// Put up out of memory alert
AlertDialog dialogError = new AlertDialog.Builder(this).create();
dialogError.setButton(DialogInterface.BUTTON_POSITIVE,"OK",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
}
);
dialogError.setMessage("Out of memory!");
dialogError.show();
}
catch (Exception e) {
e.printStackTrace();
}
}
My Problem
I take a picture with my android device. I then decode that picture from file.
Bitmap photo = BitmapFactory.decodeFile(EXTERNAL_IMAGE_PATH+File.separator+this._currentPhotoName+JPEG_FILE_SUFFIX);
if (photo == null && data != null)
photo = (Bitmap) data.getExtras().get("data");
else if (data == null && photo == null)
Log.e("CCPhotoManager","Can't find image from file or from intent data.");
I then check that picture and see whether it needs to be rotated to the correct orientation.
try {
ExifInterface exif = new ExifInterface(EXTERNAL_IMAGE_PATH+File.separator+this._currentPhotoName+JPEG_FILE_SUFFIX);
int rotation = CCDataUtils.exifToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL));
Log.v("CCPhotoManager", "Rotation:"+rotation);
if (rotation > 0) {
photo = this.convertSavedImageToCorrectOrientation(EXTERNAL_IMAGE_PATH+File.separator+this._currentPhotoName+JPEG_FILE_SUFFIX, photo, rotation);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
If it does need rotating I call this method.
public Bitmap convertSavedImageToCorrectOrientation(String filePath,Bitmap photo,int rotation) {
Log.d("CCPhotoManager", "Changing Orientation of photo located at: "+filePath+" Rotating by:"+rotation);
int width = photo.getWidth();
int height = photo.getHeight();
Matrix matrix = new Matrix();
matrix.preRotate(rotation);
Bitmap adjusted = Bitmap.createBitmap(photo, 0, 0, width, height, matrix, true);
try {
FileOutputStream out = new FileOutputStream(filePath);
adjusted.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
return adjusted;
}
I am getting Out of Memory complaints if the convertSavedImageToCorrectOrientation is called on the line Bitmap adjusted = Bitmap.createBitmap(photo,0,0,width,height,matrix,true);
This is only the case on the Samsung Galaxy S3. It works fine on the Samsung Galaxy Ace, HTC Hero and the Sony Xperia U.
Here is the error.
10-17 14:33:33.950: E/AndroidRuntime(12556): java.lang.OutOfMemoryError
10-17 14:33:33.950: E/AndroidRuntime(12556): at android.graphics.Bitmap.nativeCreate(Native Method)
10-17 14:33:33.950: E/AndroidRuntime(12556): at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
10-17 14:33:33.950: E/AndroidRuntime(12556): at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
It's a massive amount of memory too.
10-17 14:33:33.945: E/dalvikvm-heap(12556): Out of memory on a 31961104-byte allocation.
I think its something to do with the amount of Bitmaps around but I'm not sure how to stop this error from happening.
I know you can call .recycle(); on them but it doesn't seem to work.
My Question
How do I correctly handle my Bitmaps so I don't have this OOM problem?
Thanks in advance
For out of memory issue
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
I had the exact same issue, doing the exact same thing on the exact same device! Unfortunately in my case the image needed to be submitted to a webservice, using the full size, original. What worked for me was turning on largeHeap in the application element of the manifest.
This will not solve the issue permanently - its possible that a device will come along with an even larger camera and the images will not fit in memory even with largeHeap enabled. To catch this extreme edge case I also put a try catch around the code that rotates the image, and just displayed a nice error to the user.
A fuller solution would be to write your own jpeg manipulation code that can rotate a jpeg using a stream based approach so that the image never needs to be loaded into memory.
Here is a more complete example of how to resize/rotate, taken in part from the Android Developers guide (change REQ_WIDTH and REQ_HEIGHT):
private static final int REQ_WIDTH = 450;
private static final int REQ_HEIGHT = 450;
/**
* Resize, crop, rotate and Inserts the picture on the layout.
*
* #param mImageView to insert the bitmap.
* #param imageURI from wich to obtain the bitmap.
*
*/
private void setPic(ImageView mImageView, String imageURI) {
// Get the original bitmap dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageURI, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, REQ_HEIGHT, REQ_WIDTH);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imageURI, options);
//need rotation?
float rotation = rotationForImage(getActivity(), Uri.fromFile(new File(imageURI)));
if (rotation != 0) {
//rotate
Matrix matrix = new Matrix();
matrix.preRotate(rotation);
mImageView.setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, REQ_HEIGHT, REQ_WIDTH, matrix, true));
} else {
//use the original
mImageView.setImageBitmap(BitmapFactory.decodeFile(imageURI, options));
}
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public static float rotationForImage(Context context, Uri uri) {
try {
if (uri.getScheme().equals("content")) {
String[] projection = { Images.ImageColumns.ORIENTATION };
Cursor c = context.getContentResolver().query(uri, projection, null, null, null);
if (c.moveToFirst()) {
return c.getInt(0);
}
} else if (uri.getScheme().equals("file")) {
ExifInterface exif = new ExifInterface(uri.getPath());
int rotation = (int) exifOrientationToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL));
return rotation;
}
return 0;
} catch (IOException e) {
Log.e(TAG, "Error checking exif", e);
return 0;
}
}
private static float exifOrientationToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}