開發android Camera的時候,發現一個問題,就是拍照後圖檔的方向是錯的。如何避免他?可以讀取照片的exif資訊,exif資訊存儲了包括時間,照片方向等照片的全部資訊。具體步驟如下。
ExifInterface exif = null;
String TAG_ORIENTATION=null;
try {
exif = new ExifInterface(getPhotoPath());
TAG_ORIENTATION=exif.getAttribute(ExifInterface.TAG_ORIENTATION);
Log.d(TAG,"exif方向: "+TAG_ORIENTATION);
} catch (IOException e) {
e.printStackTrace();
}
getPhotoPath() 方法是獲得圖檔的路徑,比如/sdcard/1.jpg
我用四個方向進行拍照。經過列印發現,列印的結果分别是6,8,3,1
經過源碼查詢發現,這幾個值是系統定義的方向分别對應應ExifInterface.ORIENTATION_ROTATE_90,ExifInterface.ORIENTATION_ROTATE_270,ExifInterface.ORIENTATION_ROTATE_180和0度
豎屏模式下,逆時針旋轉90度,exif列印結果是1,就是0度,就是攝像頭的正方向,由此可見android手機的攝像頭是橫屏方向安裝上的
是以我們可以根據exif資訊旋轉bitmap。
try {
ExifInterface exifInterface = new ExifInterface(file.getPath());
int result = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
int rotate = 0;
switch(result) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
default:
break;
}
catch (IOException e) {
e.printStackTrace();
}
下面是旋轉bitmap的方法
public static Bitmap rotate(Bitmap b, int degrees,String filePath, int reqWidth, int reqHeight) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees,
(float) b.getWidth() / 2, (float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(
b, 0, 0, b.getWidth(), b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {
// 建議大家如何出現了記憶體不足異常,最好return 原始的bitmap對象。.
return getSampledBitmap(filePath, reqWidth, reqHeight);
}
}
return b;
}
public static Bitmap getSampledBitmap(String filePath, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = (int) FloatMath.floor(((float) height / reqHeight) + 0.5f); //Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = (int) FloatMath.floor(((float) width / reqWidth) + 0.5f); //Math.round((float)width / (float)reqWidth);
}
}
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}