Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android圖片處理:識別圖像方向並顯示實例教程

Android圖片處理:識別圖像方向並顯示實例教程

編輯:關於Android編程

在Android中使用ImageView顯示圖片的時候發現圖片顯示不正,方向偏了或者倒過來了。
解決這個問題很自然想到的分兩步走:
1、自動識別圖像方向,計算旋轉角度;
2、對圖像進行旋轉並顯示。

一、識別圖像方向
首先在這裡提一個概念EXIF(Exchangeable Image File Format,可交換圖像文件),具體解釋參見Wiki。
簡而言之,Exif是一個標准,用於電子照相機(也包括手機、掃描器等)上,用來規范圖片、聲音、視屏以及它們的一些輔助標記格式。
Exif支持的格式如下:
圖像
壓縮圖像文件:JPEG、DCT
非壓縮圖像文件:TIFF
不支持:JPEG 2000、PNG、GIF
音頻
RIFF、WAV
Android提供了對JPEG格式圖像Exif接口支持,可以讀取JPEG文件metadata信息,參見ExifInterface.
這些Metadata信息總的來說大致分為三類:日期時間、空間信息(經緯度、高度)、Camera信息(孔徑、焦距、旋轉角、曝光量等等)。

二、圖像旋轉
Android中提供了對Bitmap進行矩陣旋轉的操作,參見Bitmap提供的靜態createBitmap方法. 
public static Bitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter) 

IllegalArgumentException if the x, y, width, height values are outside of the dimensions of the source bitmap. 
到此這兩個問題理論上都解決了,開始實際操作一下吧,參照以下代碼。
復制代碼 代碼如下:
public class IOHelper {
......
/** 從給定路徑加載圖片*/
public static Bitmap loadBitmap(String imgpath) {
return BitmapFactory.decodeFile(imgpath);
}
/** 從給定的路徑加載圖片,並指定是否自動旋轉方向*/
public static Bitmap loadBitmap(String imgpath, boolean adjustOritation) {
if (!adjustOritation) {
return loadBitmap(imgpath);
} else {
Bitmap bm = loadBitmap(imgpath);
int digree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(imgpath);
} catch (IOException e) {
e.printStackTrace();
exif = null;
}
if (exif != null) {
// 讀取圖片中相機方向信息
int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
// 計算旋轉角度
switch (ori) {
case ExifInterface.ORIENTATION_ROTATE_90:
digree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
digree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
digree = 270;
break;
default:
digree = 0;
break;
}
}
if (digree != 0) {
// 旋轉圖片
Matrix m = new Matrix();
m.postRotate(digree);
bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
}
return bm;
}
}
......
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved