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

大憨熊 提交于 2019-12-24 03:54:06

问题


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?

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


回答1:


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;    
 }


来源:https://stackoverflow.com/questions/20728684/how-to-check-whether-an-image-is-captured-in-portrait-mode-or-landscape-mode-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!