我正在尝试创建一个应用,让用户点击按钮并选择图像。
我使用此问题的第二个答案提示用户输入图片:How to pick an image from gallery (SD Card) for my app?
但有时如果我选择的图像在图库中看起来是正确的,当我显示它时会有一个错误的方向(我读到这通常发生在相机拍摄的照片上,因为它们保存了它们的旋转{ {1}})
因此,当用户选择图像时,此代码会运行:
ExifInterface
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri si = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(si);
Bitmap image = Utils.decodeUri(this, si);
addPerson(selectedName, selectedDate, image);
imageStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
将此人添加到列表中并调用此处的addPerson()
:
saveData()
在try {
FileOutputStream out = new FileOutputStream(new File(folder, person.getName() + ".png"));
person.getImage().compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
};
上运行此代码以加载项目:
onCreate()
但是当我运行上面的代码时,它最终会出现黑色图像,当我调试它时Bitmap notRotated = BitmapFactory.decodeFile(file.getPath());
Matrix matrix = new Matrix();
ExifInterface exif = new ExifInterface(file.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = Utils.exifToDegrees(rotation);
if(rotation != 0f)
matrix.preRotate(rotationInDegrees);
image = Bitmap.createBitmap(notRotated, 0, 0, notRotated.getWidth(), notRotated.getHeight(), matrix, true);
notRotated.recycle();
始终为0,尽管显然有不同旋转的图像。
如何解决此问题?
编辑:
这是我的代码,用于对我的位图进行缩减以防止rotation
s:
OutOfMemoryException
我的下采样会影响旋转吗?
答案 0 :(得分:0)
好的,感谢@CommonsWare的帮助。我指出的代码中的一些错误是以PNG格式保存位图,而不是在以错误的方式保存和使用ExifInterface之前旋转它们。我将保存格式更改为JPEG并使用了ExifInterface的this example(使用自定义ExifInterface)。