简体   繁体   中英

How to check whether an image is captured in portrait mode or landscape mode using camera in android?

I am creating an app which open the photo gallery and a photo will be displayed in another activity by selecting that photo from the gallery. My problem is that the photos which I captured in portrait mode will be rotated after display. But the photos which I captured in landscape mode will be displayed correctly.

That's why, I have to check whether an image is captured in portrait mode or landscape mode using camera in android so that I can rotate the portrait captured photos. Can anyone help me how to do that?

NB: The width and height are same both in portrait captured image and landscape captured image.

You can always check the rotation of the image using Matrix and rotate it accordingly.

This code goes in onActivityResult-->

    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inPurgeable = true;

        Bitmap cameraBitmap = BitmapFactory.decodeFile(filePath);//get file path from intent when you take iamge.
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);


        ExifInterface exif = new ExifInterface(filePath);
        float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);  
        System.out.println(rotation);

        float rotationInDegrees = exifToDegrees(rotation);
        System.out.println(rotationInDegrees);

        Matrix matrix = new Matrix();
        matrix.postRotate(rotationInDegrees);

        Bitmap scaledBitmap = Bitmap.createBitmap(cameraBitmap);
        Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
        FileOutputStream fos=new FileOutputStream(filePath);
        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();

OnActivityResult Code Ends here.

This function below is used to get rotation:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM