public static boolean rotateBitmapByExifAndSave(File targetFile){
if (targetFile==null || !targetFile.exists() || !targetFile.canRead() || !targetFile.canWrite())
return false;
boolean isSucceed = false;
// detect if photo is need to be rotated
try {
final Matrix matrix = new Matrix();
ExifInterface exifReader = new ExifInterface(targetFile.getAbsolutePath());
int orientation = exifReader.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
boolean isRotationNeeded = true;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default: // ExifInterface.ORIENTATION_NORMAL
// Do nothing. The original image is fine.
isRotationNeeded = false;
isSucceed = true;
break;
}
if (isRotationNeeded){
BitmapFactory.Options bmfOtions = new BitmapFactory.Options();
Bitmap bitmap = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(targetFile);
bitmap = BitmapFactory.decodeStream(fileInputStream,null,bmfOtions);
} catch (FileNotFoundException e){
isSucceed = false;
}
finally {
if (fileInputStream != null)
try {
fileInputStream.close();
} catch (IOException e) {}
}
if (bitmap!=null){
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
isSucceed = ImageUtils.saveBitmapToFile(bitmap, targetFile, 100);
bitmap.recycle();
}
}
} catch (IOException e) {
Log.e("ImageUtils", e);
} catch (Exception e) {
// like there is no EXIF support?
Log.e("ImageUtils", e);
} catch (Throwable e) {
// stupid Out of VM's memory
Log.e("ImageUtils", e.toString());
}
return isSucceed;
}
我用這種方法來旋轉設備相機拍攝的原始照片。如今相機可能比8MPix更大(三星Galaxy S4擁有13萬像素相機)。即使使用較少的MPix相機(我的5 MP,2592 x 1944像素與ARGB_888結合需要19Mb根據官方文檔)我已經得到了OutOfMemory。所以問題是如何旋轉照片而不損失它的初始分辨率和質量?如何在旋轉圖像時避免OutOfMemory ex?
你解決了這個問題嗎? @斯坦 – bentzy
嘿斯坦我需要這個問題的答案。如果可以的話幫我一把!謝謝 – therealprashant