問題所在
最近做了一個需求躁倒,從手機相冊中獲取圖片并進行顯示,做完測試都沒有問題耻讽,后來突然發(fā)現(xiàn)三星的手機取出的圖片是左轉(zhuǎn)了90度的察纯。wtf~~。(文章轉(zhuǎn)自自己的博客针肥,這里的最近其實是16年5月)
下面這個是不正常的(狀態(tài)欄請無視饼记,隨便拿了個公司的測試機)
正常應該是這樣的
解決方案
我們需要用到一個叫做 ExifInterface的類,google官方對其的描述是:
This is a class for reading and writing Exif tags in a JPEG file or a RAW image file.
Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF and RAF.
Attribute mutation is supported for JPEG image files.
根據(jù)描述這是一個用來操作圖片exiftag信息的類
解決的具體辦法
不是所有的圖片都需要處理慰枕,先檢查
talk is cheap,show you my code
public int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
這是一個檢查圖片的旋轉(zhuǎn)度數(shù)的方法(三星我遇到的都是90)具则,所以,如果你收到返回為90.那就應該要進行處理具帮。
既然你知道有問題了博肋,是不是要處理呢?
talk is cheap,show you my code
public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
Bitmap returnBm = null;
// 根據(jù)旋轉(zhuǎn)角度蜂厅,生成旋轉(zhuǎn)矩陣
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
// 將原始圖片按照旋轉(zhuǎn)矩陣進行旋轉(zhuǎn)匪凡,并得到新的圖片
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
}
return returnBm;
}
你需要把path轉(zhuǎn)為bitmap,然后此方法是根據(jù)你傳入的角度掘猿,進行旋轉(zhuǎn)(檢測獲取到是多少病游,就傳入多少就行)。
再提供一個path轉(zhuǎn)bitmap的方法
public static Bitmap getBitmapCompress720P(String pathName) {
int targetWidth = 720;
int targetHeight = 1080;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap;
float imgWidth = options.outWidth;
float imgHeight = options.outHeight;
int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
options.inSampleSize = 1;
if (widthRatio > 1 || widthRatio > 1) {
if (widthRatio > heightRatio) {
options.inSampleSize = widthRatio;
} else {
options.inSampleSize = heightRatio;
}
}
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(pathName, options);
return bitmap;
}
這個方法是path轉(zhuǎn)bitmap稠通。對圖片進行了縮放衬衬,因為bitmap在set imageview的時候,其實你取出來的會很大改橘,多半會失敗滋尉,反正要壓縮,不如這里壓縮唧龄,上面方法是設置的720P的壓縮兼砖,你可以直接改,也可以進行擴展既棺。
注意事項
一般來說讽挟,需要從相冊取圖片的需求都伴隨著上傳,如果你不能直接bitmap上傳丸冕,那可能還需要轉(zhuǎn)回到path存到本地耽梅,這里是一個比較耗時的過程,建議使用異步胖烛,并且眼姐,在上傳時去做轉(zhuǎn)存诅迷。