Picture taken from camera or gallery when using in imageview its orientation getting changed, and sometimes vertically stretched in Android

后端 未结 1 803
长发绾君心
长发绾君心 2021-01-05 10:40

In my application I have to capture image from camera or import from gallery, show it in imageview in activity. Everything is fine, I am getting image from both and able to

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 11:12

    The images has different orientations so it rotates according to the orientation when putting on imageview. You can check the orientation of the photo from properties of image. To set the image in proper manner you can use the following code...

         int rot=getCameraPhotoOrientation(this,Uri,picturePath);
             if(rot!=0)
             bitmap=new RotateOrientation().RotateOrientationCall(bitmap,rot);
    

    The getCameraPhotoOrientation Method:-

     public static int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath){
         int rotate = 0;
         try {
             context.getContentResolver().notifyChange(imageUri, null);
             File imageFile = new File(imagePath);
             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.d(TAG, "Exit orientation: " + orientation);
         } catch (Exception e) {
             e.printStackTrace();
         }
        return rotate;
     }
    

    Add RotateOrientation class to rotate class according to orientation.

     public class RotateOrientation  {
    
    Bitmap RotateOrientationCall(Bitmap src,float degree)
            {
    
    
            Matrix matrix=new Matrix();
            matrix.postRotate(degree);
           Bitmap bmOut = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
          return bmOut;
    
          }
              }
    

    0 讨论(0)
提交回复
热议问题