如何在Android中使用相机检查是以纵向模式还是横向模式捕获图像?

时间:2013-12-22 11:03:15

标签: android orientation photo-gallery

我正在创建一个打开照片库的应用程序,通过从库中选择该照片,将在另一个活动中显示照片。我的问题是我在纵向模式下拍摄的照片将在显示后旋转。但是我在风景模式下拍摄的照片将正确显示。

这就是为什么,我必须检查是否使用Android中的相机以纵向模式或横向模式捕获图像,以便我可以旋转捕获的肖像照片。任何人都可以帮我怎么做?

N.B。:纵向拍摄图像和风景拍摄图像的宽度和高度相同。

1 个答案:

答案 0 :(得分:3)

您始终可以使用Matrix检查图像的旋转并相应地旋转它。

此代码位于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代码在此结束。

以下功能用于旋转: -

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