安卓无法从相册加载正确方向的图片

5

我通过位图API从图库中加载图片,但是图片的方向与我保存的不同。在stackoverflow上某处我读到需要获取方向值,然后旋转矩阵。我尝试了这个方法,但我的方向值从exif接口中获取为0。

        int desiredImageWidth = 310;  // pixels
        int desiredImageHeight = 518; // pixels

        Log.i("FA", "Image Loading "+strFileName);
        BitmapFactory.Options o = new BitmapFactory.Options();
        Bitmap newImage = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(strFileName, o), 
                                                   desiredImageWidth, 
                                                   desiredImageHeight, 
                                                   false);

        Bitmap finalBmp = getCorrectOrientedBitmap(strFileName,newImage);

        Bitmap myBitmap32 = finalBmp.copy(Bitmap.Config.ARGB_8888, true);

        Mat matImg = Utils.bitmapToMat(myBitmap32);

我的主要定位函数是
    private Bitmap getCorrectOrientedBitmap(String filename,Bitmap Source) throws IOException{

    Bitmap rotatedBitmap = null;
    ExifInterface exif = new ExifInterface(filename);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

    Matrix matrix = new Matrix();
    Log.i("FA", "orientation "+orientation);
    switch(orientation)
    {
    case 6:
        matrix.postRotate(90);
        break;
    case 3:
        matrix.postRotate(180);
        break;
    case 8:
        matrix.postRotate(270);
        break;
    }
    rotatedBitmap = Bitmap.createBitmap(Source, 0, 0, Source.getWidth(), Source.getHeight(), matrix, true);

    return rotatedBitmap;
}

我也遇到了同样的问题。但在我的情况下,来自图库的某些图片以不同的方向出现。你能发布一下解决方案吗? - user2376920
1个回答

0

如果你从getAttributeInt得到了0,那么我认为这只是意味着你的“旋转”图像中没有存储任何方向信息。你可以使用在线工具或下载一个好的图像查看器来进行独立的双重检查。

你是否尝试在另一台设备上运行此代码?你的测试设备是否可能不保存方向标签?

这个页面有一些很好的示例代码可以做你想做的事情,也许你可以在那里找到一些改进。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接