Android通過ExifInterface判斷Camera圖片方向的方法
Android的Camera相關(guān)應(yīng)用開發(fā)中,有一個必須搞清楚的知識點,就是Camera的預(yù)覽方向和拍照方向
圖像的Sensor方向:手機Camera的圖像數(shù)據(jù)都是來自于攝像頭硬件的圖像傳感器(Image Sensor),這個Sensor被固定到手機之后是有一個默認的取景方向的,這個方向如下圖所示,坐標原點位于手機橫放時的左上角:
android應(yīng)用里使用相機圖片時必須要考慮的一個問題就是圖片朝向,只有判斷對朝向才能調(diào)整圖片從而更好的展現(xiàn)。本文將介紹一種通過ExifInterface判斷圖片朝向的方法!上代碼:
/** * 利用給定路徑下的圖片設(shè)置ImageView * @param imgPath 手機圖片文件路徑 * @param imgView 需要設(shè)置的ImageView */ public void setImg(String imgPath, ImageView imgView) { File file = new File(imgPath); if (file.exists() && file.canRead()) { // -------1.圖片縮放-------- // 手機屏幕信息 DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); int dw = metric.widthPixels; // 屏幕寬 int dh = metric.heightPixels; // 屏幕高 // 加載圖像,只是為了獲取尺寸 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 設(shè)置之后可以獲取尺寸信息 Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options); // 計算水平和垂直縮放系數(shù) int heightRatio = (int) Math.ceil(options.outHeight / (float) dh); int widthRatio = (int) Math.ceil(options.outWidth / (float) dw); // 判斷哪個大 if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } // 圖片縮放 options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(imgPath, options); // -------2.判斷圖片朝向-------- try { ExifInterface exif = new ExifInterface(imgPath); int degree = 0; // 圖片旋轉(zhuǎn)角度 if (exif != null) { int orientation = exif.getAttributeInt( ExifInterface.TAG_ORIENTATION, -1); if (orientation != -1) { 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; default: break; } } } if (degree != 0) { // 圖片需要旋轉(zhuǎn) int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preRotate(degree); Bitmap mRotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); imgView.setImageBitmap(mRotateBitmap); } else { imgView.setImageBitmap(bitmap); } } catch (IOException e) { } } }
本代碼包含兩大功能:
1. 圖片縮放:原始圖片一般比較大,經(jīng)過縮小才能使用;
2. 圖片旋轉(zhuǎn):由于用戶拍照時手機角度不同,所得照片可能需要旋轉(zhuǎn)。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
Android SDK Manager更新、下載速度慢問題解決辦法
這篇文章主要介紹了Android SDK Manager更新、下載速度慢問題解決辦法的相關(guān)資料,需要的朋友可以參考下2017-05-05Flutter的鍵值存儲數(shù)據(jù)庫使用示例詳解
這篇文章主要為大家介紹了Flutter的鍵值存儲數(shù)據(jù)庫使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08Android中使用Notification實現(xiàn)狀態(tài)欄的通知
本文主要介紹了android利用Notification實現(xiàn)狀態(tài)欄的通知的示例代碼。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04詳解Android 多級聯(lián)動控件實現(xiàn)思路討論
這篇文章主要介紹了詳解Android 多級聯(lián)動控件實現(xiàn)思路討論,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11