Percy

拍摄人像时Android相机意图保存图像风景

android

我环顾四周,但似乎并没有解决这个非常恼人的问题的可靠答案。

我以纵向拍摄照片,然后单击“保存/放弃”,按钮也以正确的方向放置。问题是当我随后在横向上检索图像时(图像已逆时针旋转90度)

我不想强迫用户以特定方向使用相机。

有没有办法检测照片是否以人像模式拍摄,然后解码位图并将其向上翻转?


阅读 375

收藏
2020-12-07

共1个答案

小编典典

照片始终以相机内置在设备中的方向拍摄。为了使图像正确旋转,您必须读取存储在图片中的方向信息(EXIF元数据)。在那里存储了拍摄图像时设备的方向。

这是一些读取EXIF数据并相应旋转图像的代码: file是图像文件的名称。

BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, bounds);

BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(file, opts);
ExifInterface exif = new ExifInterface(file);
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) :  ExifInterface.ORIENTATION_NORMAL;

int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;

Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);

更新2017-01-16

随着25.1.0支持库的发布,引入了ExifInterface支持库,这也许应该使对Exif属性的访问更容易。

2020-12-07