我试图制作一个应用程序,允许用户从图库中选择图像/拍照并将结果设置为位图。当我测试该应用程序时,我发现三星设备的旋转有问题。
搜索了一段时间后,我发现旋转不是由谷歌定义的,而是制造商自己和三星似乎有一些不同的设置。此外,还有一些建议使用另一种方法来检查旋转。
如何解决问题?(注:不仅拍照,图库的图片也有同样的旋转问题)
以下是从提供的文件路径获取位图的代码:
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
in = mContentResolver.openInputStream(uri);
Bitmap b = BitmapFactory.decodeStream(in, null, o2);
in.close();
return b;
} catch (FileNotFoundException e) {
Log.e(TAG, "file " + path + " not found");
} catch (IOException e) {
Log.e(TAG, "file " + path + " not found");
}
return null;
}
感谢您的帮助
我认为您正在寻找的是从图像中读取 exif 旋转并相应地旋转它。我知道三星设备存在图像无法正确面对的问题,但您可以像这样纠正:
首先,您必须从图像中读取Exif旋转:
ExifInterface exif = new ExifInterface(pathToFile);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
有了这些信息,您可以纠正图像的旋转,不幸的是,这有点复杂,它涉及使用矩阵旋转位图。您可以像这样创建矩阵:
Matrix matrix = new Matrix();
switch (rotation) {
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
break;
}
最后,您可以创建正确旋转的位图:
int height = bitmap.getHeight();
int width = bitmap.getWidth();
Bitmap correctlyRotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
为了避免内存不足异常,您应该在创建正确旋转的位图后回收旧的未正确旋转的位图,如下所示:
bitmap.recycle();