I'm writing a Xamarin forms android application where I'm taking images from gallery. I want to upload those images to server, So I need byte[] from it. I'm scaling and compressing those images and then taking byte[] from it. My problem is when I compress the image, the image is changing it's orientation from portrait to landscape. I've tried by using 'ExifInterface' class and changing the image orientation but it's not working. Below is the my complete code :-
protected override async void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
if (resultCode == Result.Canceled)
return;
try {
var mediafile = await data.GetMediaFileExtraAsync (Forms.Context);
byte[] data1 = ReadFully (mediafile.GetStream ());
byte[] resizedImage = ResizeImageAndroid (data1, 60, 60, mediafile);
var imageStream = new ByteArrayContent (resizedImage);
imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue ("attachment") {
FileName = Guid.NewGuid () + ".Png"
};
var multi = new MultipartContent ();
multi.Add (imageStream);
HealthcareProfessionalDataClass lDataClass = HealthcareProfessionalDataClass.Instance;
lDataClass.Thumbnail = multi;
App.mByteArrayOfImage = data1;
System.Diagnostics.Debug.WriteLine (mediafile.Path);
MessagingCenter.Send<IPictureTaker,string> (this, "picturetaken", mediafile.Path);
} catch (Java.Lang.Exception e) {
e.PrintStackTrace ();
}
}
public static byte[] ReadFully (System.IO.Stream input)
{
using (var ms = new MemoryStream ()) {
input.CopyTo (ms);
return ms.ToArray ();
}
}
public static byte[] ResizeImageAndroid (byte[] imageData, float width, float height, MediaFile file)
{
try {
// Load the bitmap
var options = new BitmapFactory.Options ();
options.InJustDecodeBounds = true;
// Calculate inSampleSize
options.InSampleSize = calculateInSampleSize (options, (int)width, (int)height);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
Bitmap originalImage = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length, options);
Bitmap resizedImage = Bitmap.CreateScaledBitmap (originalImage, (int)width, (int)height, false);
using (var ms = new MemoryStream ()) {
resizedImage.Compress (Bitmap.CompressFormat.Png, 0, ms);
resizedImage = changeOrientation (file, resizedImage);
return ms.ToArray ();
}
} catch (Java.Lang.Exception e) {
e.PrintStackTrace ();
return null;
}
}
public static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int height = options.OutHeight;
int width = options.OutWidth;
int inSampleSize = 4;
if (height > reqHeight || width > reqWidth) {
int halfHeight = height / 2;
int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
static Bitmap changeOrientation (MediaFile mediafile, Bitmap bitmap)
{
var exifInterface = new ExifInterface (mediafile.Path);
int orientation = exifInterface.GetAttributeInt (ExifInterface.TagOrientation, 0);
var matrix = new Matrix ();
switch (orientation) {
case 2:
matrix.SetScale (-1, 1);
break;
case 3:
matrix.SetRotate (180);
break;
case 4:
matrix.SetRotate (180);
matrix.PostScale (-1, 1);
break;
case 5:
matrix.SetRotate (90);
matrix.PostScale (-1, 1);
break;
case 6:
matrix.SetRotate (90);
break;
case 7:
matrix.SetRotate (-90);
matrix.PostScale (-1, 1);
break;
case 8:
matrix.SetRotate (-90);
break;
default:
return bitmap;
}
try {
Bitmap oriented = Bitmap.CreateBitmap (bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
bitmap.Recycle ();
return oriented;
} catch (OutOfMemoryError e) {
e.PrintStackTrace ();
return bitmap;
} catch (System.Exception e) {
System.Diagnostics.Debug.WriteLine (e.Message);
return bitmap;
}
}
If someone have a solution to my problem please let me know.
I am not sure if I miss read it but it feels the matrix is not being assigned to any image? So any change you make to the matrix you will never see.
The way I went around implementing this was:
Matrix mtx = new Matrix();
ExifInterface exif = new ExifInterface(fileName);
string orientation = exif.GetAttribute(ExifInterface.TagOrientation);
switch (orientation)
{
case "6": // portrait
mtx.PreRotate(90);
resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
mtx.Dispose();
mtx = null;
break;
case "1": // landscape
break;
case "8": // Selfie ORIENTATION_ROTATE_270 - might need to flip horizontally too...
mtx.PreRotate(270);
resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
mtx.Dispose();
mtx = null;
break;
}
This was the matrix .preRotate is assigned to the Bitmap.CreateBitmap(), then you return this resized bitmap.
I hope this helps :)
Related
I have an activity where the user can open the camera like so
getPictureUri(createImageFromFile = true)?.let {
photoUri = it
openCameraActivity(REQUEST_IMAGE_CAPTURE, it)
} ?: photoViewModel.onRequestUriError()
openCamera is an Activity Extension that looks like this
fun Activity.openCameraActivity(requestCode: Int, pictureUri: Uri) {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.resolveActivity(packageManager)?.also {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri)
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
startActivityForResult(takePictureIntent, requestCode)
}
}
}
We write the image to a file when we get it back, and store the photoUri in the app somewhere. It works great! The issue is that some users have super high megapixel cameras, like 64mp, and when they take a picture it tries to display in the UI and it crashes.
FATAL EXCEPTION: main
Process: co.app.staging, PID: 27859
java.lang.RuntimeException: Canvas: trying to draw too large(256576512bytes) bitmap.
Is there a way I can limit the camera resolution on this? I could turn the quality down but that seems like a bandaid at best. What are some decent solutions for this?
I tried this way to draw bitmap on canvas from URI, try this:
(Explanation given below code)
private void drawBitmapUriOnCanvas(Uri selectedImage) {
if (selectedImage != null) {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(
selectedImage), null, bmpFactoryOptions);
bmpFactoryOptions.inSampleSize = 2;
bmpFactoryOptions.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
selectedImage), null, bmpFactoryOptions);
Bitmap alteredBitmap;
if (bmp != null) {
if (getDeviceRam(this) <= 1024) {
bmp = getResizedBitmap(bmp, displayWidth);
}
bmp = checkAndRotateBitmap(bmp);
alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(5);
paint.setAntiAlias(true);
Matrix matrix = new Matrix();
canvas.drawBitmap(bmp, matrix, paint);
(now alteredBitmap is processed bitmap and you can use it)
}
} catch (FileNotFoundException e) {
Toast.makeText(this, "Error reading Image Metadata", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
Other included methods:
public static long getDeviceRam(Context context) {
ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;
long fileSizeInKB = totalMemory / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
return fileSizeInKB / 1024;
}
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
Here, first of all i decoded image uri using BitmapFactory, then i checked device ram and it it was of 1GB then i resize the bitmap other wise original bitmap will be ok for next step,
And next was simply drawing bitmap on canvas and you will get alteredBitmap will is processed bitmap and it will be easy to use.
If this will not work then there is another option for completing your requirement and it was given below:
Bitmap bitmap = getBitmapFromGallery(selectedImage.getPath(), 800, 800);
private Bitmap getBitmapFromGallery(String path, int width, int height) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
// if you use image from camera then in some cases it will rotated automatically like it was captured landscape but displays portrait then you have to use method `checkAndRotateBitmap()` which was also given below
// bitmap = checkAndRotateBitmap(bitmap);
return bitmap;
}
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) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Bitmap checkAndRotateBitmap(Bitmap bmp) {
try {
ExifInterface ei = new ExifInterface(imgPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = Helper.rotateImage(bmp, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = Helper.rotateImage(bmp, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = Helper.rotateImage(bmp, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bmp;
}
return rotatedBitmap;
} catch (IOException e) {
e.printStackTrace();
return bmp;
}
}
EDIT
for more information on how getBitmapFromGallery() method works, you should have look at https://medium.com/android-news/loading-large-bitmaps-efficiently-in-android-66826cd4ad53
That's all my friend, now try one of the methods for your requirement and let me know if this will work or not, also help me improve my answer if anything was wrong..Thank you!!
I am using the following method to get the Bitmap from a Uri :
private static Bitmap getBitmapFromUri(#NonNull Context context, #NonNull Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
context.getContentResolver().openFileDescriptor(uri, "r");
assert parcelFileDescriptor != null;
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
The problem is, I am sometimes getting OOM errors in the return statement from Crashlytics. I assume it is happening because the selected image is of a large size. How do modify it so as to return the best quality scaled down version of Bitmap so that it does not cause Out of memory error?
Edit I have posted an answer myself. Please have a look and let me know it is the correct way to do it.
You have to resize your image before decode. Here is my code to decode an image and display it in an image view.
private void loadImage(Uri u, String path) {
try {
ContentResolver cr = context.getContentResolver();
InputStream in;
in = cr.openInputStream(u);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
in = cr.openInputStream(u);
Bitmap bitmap = BitmapFactory.decodeStream(in, null, o2);
in.close();
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), getRotation(path), true);
int nh = (int) ( rotatedBitmap.getHeight() * (512.0 / rotatedBitmap.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(rotatedBitmap, 512, nh, true);
String pathTest = MediaStore.Images.Media.insertImage(context.getContentResolver(), scaled, "Title", null);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(Uri.decode(Uri.parse(pathTest).toString()), mPicture, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mPicture.setImageBitmap(loadedImage);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
}
});
} catch (Exception e) {
//Toast.makeText(context, context.getString(R.string.fail_to_load_image), Toast.LENGTH_SHORT).show();
Log.e("TAG", e.toString());
}
}
private Matrix getRotation(String pathPetPicture) {
Matrix matrix = new Matrix();
try {
ExifInterface exif = new ExifInterface(pathPetPicture);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
switch (rotation) {
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
break;
}
} catch (Exception e) {
Log.e("TAG", e.toString());
}
return matrix;
}
Try something like this...
// decode image
public Bitmap decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
May it help.
and if you want Loading Large Bitmaps Efficiently then follow this
Bitmap bm;
bm = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(filepath), 100, 100, true);
mPicture = new ImageView(context);
mPicture.setImageBitmap(bm);
Use this and replace your code with this in getBitmapFromUri()
I read all the answers and this is what I am planning to do, tell me if it will work or not. In my Application class, in onCreate(), I store the device width and height in pixels in the SharedPreferences. In the modified code, I scale the bitmap according to the device pixels. Hope it will spare me the OOM error.
private static Bitmap getBitmapFromUri(#NonNull Context context, #NonNull Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
context.getContentResolver().openFileDescriptor(uri, "r");
assert parcelFileDescriptor != null;
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
TinyDB tinyDB = new TinyDB(context);
int maxSize = Math.min(tinyDB.getInt(AppConstants.DEVICE_WIDTH, 720), tinyDB.getInt(AppConstants.DEVICE_HEIGHT, 1080));
int outWidth;
int outHeight;
int inWidth = image.getWidth();
int inHeight = image.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
return Bitmap.createScaledBitmap(image, outWidth, outHeight, false);
}
Use Glide or Picasso libraries:
Replace path with local folder path or server url
Glide.with (context).load (path).asBitmap().into(imageView);
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.
On Android, i'm trying to crop an image bitmap taken from camera to a fixed width / width which is smaller than the original photo taken, but when I create the cropped image the result always gets rotated (even if no matrix is defined) see http://i.imgur.com/MppWH69l.png
as original and http://i.imgur.com/C4WVtwZl.png as the cropped Image, which is being rotated and shows up incorrectly.
Why does the createBitmap method rotates the bitmap to be drawn in the destination bitmap.
Relevant code as follows
try { int dstWidth = params[0].intValue();
int dstHeight = params[1].intValue();
int targetSize = Math.min(dstWidth, dstHeight);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(mPhotoUri), null, options);
//calculate min inSampleSize for avoiding memory problems
options.inSampleSize = calculateImageInSampleSize(options, targetSize, targetSize);
options.inJustDecodeBounds = false;
Bitmap originalPhotoBitmap = BitmapFactory.decodeStream(getActivity().getContentResolver()
.openInputStream(mPhotoUri), null, options);
mOriginalBitmap = Bitmap.createBitmap(originalPhotoBitmap, originalPhotoBitmap.getWidth() - targetSize,
originalPhotoBitmap.getHeight() - targetSize, targetSize, targetSize);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//codefor inSampleSize calculation from http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap
private int calculateImageInSampleSize(BitmapFactory.Options originalSize, int targetWidth, int targetHeight) {
final int width = originalSize.outWidth;
final int height = originalSize.outHeight;
int inSampleSize = 1;
if (height > targetHeight || width > targetWidth) {
final int halfHeight = height /2;
final int halfWidth = width /2;
while ((halfHeight /inSampleSize) > targetHeight &&
(halfWidth / inSampleSize) > targetWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
every device followed different orientation in camera so you followed this example solve your problem
private Bitmap imageRotating(String filePath){
try{
ExifInterface exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
return rotateBitmap(decodeSampledBitmapFromResource(filePath,150,224), orientation);
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
try{
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
Hello I am working on one android app where I need to capture the image using camera intent and set the bitmap in the imageview but here bitmap is rotated by 90 degree. I have checked many threads of stackoverflow like Photo rotate 90 degree while capture in some phones but did not work for me.
Here when I am executing this exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); then it is returning 0 ORIENTATION_UNDEFINED and in my getImage function no condition is satisfying.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
capturedPhotoName = System.currentTimeMillis() + ".png";
File photo = new File(Environment.getExternalStorageDirectory(),
capturedPhotoName);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERA_INTENT_REQUEST);
onActivityResult
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,
selectedImage);
bitmap = Util.getImage(bitmap, selectedImage.toString());
mPictureImageView.setImageBitmap(bitmap);
} catch (Exception e) {
Log.e("New Issue Activity", e.toString());
}
/**
* Get the image orientation
*
* #param imagePath
* #return orietation angle
* #throws IOException
*/
public static Bitmap getImage(Bitmap bitmap, String path) throws IOException {
Matrix m = new Matrix();
ExifInterface exif = new ExifInterface(path);
int orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), m, true);
return bitmap;
}
return bitmap;
}
I implemented one photo take activity which you can take the photo and set the orientation of the photo. It is supported by every device I tested including Samsung galaxy series, tablets, sony xperia series, tablets.
You can check out my accepted answer about rotation of images on this topic:
Camera capture orientation on samsung devices in android
If you also need to save and use that image that you have rotated, saving and using the photo functions additional to my answer I gave above:
savePhoto function:
public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(),
cc.getDirectoryName());
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}
scanPhoto function:
public void scanPhoto(final String imageFileName) {
geniusPath = imageFileName;
msConn = new MediaScannerConnection(MyClass.this,
new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
}
});
msConn.connect();
}
SavePhotoTask class:
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(),
"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
}
return (null);
}
}
Try below code:-
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
ExifInterface exif = new ExifInterface(imageFile.toString());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bitmap = Utility.getOrientationFromExif(new Utility().compressImage1(imageFile.toString(),((Activity)context)),orientation);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG , 50 , bos);
Utility.java
public class Utility
{
public Bitmap compressImage1(String imageUri, Activity act)
{
String filePath = getRealPathFromURI(imageUri, act);
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not
// loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
// Bitmap bmp = decodeBitmap(Uri.parse(imageUri), 612, 816, act);
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
// setting inSampleSize value allows to load a scaled down version of
// the original image
options.inSampleSize = calculateInSampleSize(options, 612, 816);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low
// on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
return bmp;
}
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)
{
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
{
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap getOrientationFromExif(Bitmap bitmap, int orientation)
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 612;
int newHeight = 816;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
switch (orientation)
{
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
// matrix.setScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
// matrix.postScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
// matrix.postScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
// matrix.postScale(-1, 1);
matrix.postScale(scaleWidth, scaleHeight);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try
{
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
}
}
This function worked for me, try your luck.
public static Bitmap rotateImage(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
default:
break;
// etc.
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}