Android Get Orientation Of A Camera Bitmap? And Rotate Back -90 Degrees


Answer :

If a photo is taken with a digital camera or smartphone, rotation is often stored in the photo's Exif data, as part of the image file. You can read an image's Exif meta-data using the Android ExifInterface.

First, create the ExifInterface:

ExifInterface exif = new ExifInterface(uri.getPath()); 

Next, find the current rotation:

int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);   

Convert exif rotation to degrees:

int rotationInDegrees = exifToDegrees(rotation); 

where

private static int exifToDegrees(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;      } 

Then use the image's actual rotation as a reference point to rotate the image using a Matrix.

Matrix matrix = new Matrix(); if (rotation != 0) {matrix.preRotate(rotationInDegrees);} 

You create the new rotated image with the Bitmap.createBitmap method that take a Matrix as a parameter:

Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter) 

where Matrix m holds the new rotation:

Bitmap adjustedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true); 

See this tutorial for a useful source code example:

  • Read Exif information in a JPEG file.

Last answer was technically perfect, but I tried hard to create a system to manage pictures, rotate, resize, cache and load into ImageViews and I can tell it is a hell. Even when all it was done it crashes sometimes cause OutOfMemory in some devices.

My point is do not reinvent the wheel, it has a perfect design. Google itself encourage you to use Glide. It works in one line, super easy to use, lightweight in size and functions number, it manage EXIF by default, and it use memory like a charm.. It is simply black magic coded ;)

I'm not sure if Picasso also manages EXIF, but there is a quick intro to both of them:

https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

My Advice: do not waste your time and use them. You can solve your problem in one line:

Glide.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView); 

if you are Using Jetpack CameraX, inside onImageCaptured method you can access rotation degree provided by EXIF data from the imageProxy like this:

image.imageInfo.rotationDegrees 

then while setting your image you can rotate your image according to this degree


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?