Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

8.2.1 Bitmap 位圖全解析(上):建立、常用 API 與裁切縮放

編輯:Android 技術基礎

本節引言

上一節我們把 Android 裡 13 種 Drawable 掃過一遍,有沒有實際用進自己的專案?本節換主角,來談 Bitmap(位圖)的用法。

正式開始前,先把四個容易混淆的名詞分清楚:

  • Drawable:通用的圖形物件,用來承載各種格式的圖像,可以是 PNG、JPG,也可以是前面學過的 13 種 Drawable 型別。你可以把它想成一個畫框。
  • Bitmap(位圖):可以想成畫架——先把畫放上去,之後就能進行各種處理,例如讀取圖檔資訊、旋轉裁切、放大縮小。
  • Canvas(畫布):顧名思義就是畫布,可以在上面作畫。用 Paint(畫筆)畫形狀或寫字,用 Path(路徑)把多個點連成圖形。
  • Matrix(矩陣):負責圖形特效處理,例如平移、縮放、旋轉、傾斜,以及 ColorMatrix 這類顏色矩陣。

以上全都出自 Android 底層繪圖套件 android.graphics。廢話不多說,開始本節內容。官方文件:Bitmap。


1. 搞懂 Bitmap、BitmapFactory 與 BitmapFactory.Options 的關係

直接翻原始碼最快。打開 Bitmap 類別,你會看到建構子上面寫著一段註解:

大意是:Bitmap 的建構子是私有的,外部無法直接 new,只能透過 JNI 建立。既然不能自己 new,官方當然會提供一個入口,也就是 BitmapFactory。

打開 BitmapFactory 並看左側的 Structure,你會發現它幾乎全是 decodeXxx 系列方法,用各種來源形式產生 Bitmap:

接著又會發現,每個方法都有一個 Options 型別的參數。點進去一看,原來是靜態內部類 BitmapFactory.Options,用來設定解碼時的選項:

只要調整其中幾個欄位(例如把 inJustDecodeBounds 設為 true 就能避免一次性配置大量記憶體),就能在不犧牲功能的前提下降低 OOM 風險。至於 Bitmap 本身,方法非常多,我們挑常用的幾個來看。中文文件:Android 中文 API(136)—— Bitmap。


2. Bitmap 常用方法

普通方法

  • boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream):把位圖壓縮寫入指定的 OutputStream,也就是存檔。format 為 PNG、JPEG 等格式;quality 範圍 0–100,0 品質最低、100 最高(PNG 為無損格式,會忽略品質設定);stream 為輸出串流。回傳值代表是否壓縮成功。
  • void recycle():釋放位圖占用的記憶體,並把位圖標記為 Dead。
  • boolean isRecycled():判斷位圖記憶體是否已釋放。
  • int getWidth():取得位圖寬度。
  • int getHeight():取得位圖高度。
  • boolean isMutable():圖片是否可修改。
  • int getScaledWidth(Canvas canvas):取得指定密度換算後的寬度。
  • int getScaledHeight(Canvas canvas):取得指定密度換算後的高度。

靜態方法

  • Bitmap createBitmap(Bitmap src):以 src 為原圖產生不可變的新圖像。
  • Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter):以 src 為原圖建立新圖像,指定新尺寸與是否濾波。
  • Bitmap createBitmap(int width, int height, Config config):建立指定格式與尺寸的空白位圖。
  • Bitmap createBitmap(Bitmap source, int x, int y, int width, int height):以 source 為原圖,從指定座標裁出指定尺寸的新圖片。
  • Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter):同上,額外套用矩陣變換。

BitmapFactory.Options 常用欄位

  • boolean inJustDecodeBounds——設為 true 時不實際解碼、不配置記憶體,只回傳圖片的寬高資訊。
  • int inSampleSize——縮放倍數。設為 4 時寬高各為原來的四分之一,總面積為十六分之一。
  • int outWidth——解碼後可取得原始圖片寬度。
  • int outHeight——解碼後可取得原始圖片高度。
  • int inDensity——來源位圖的像素密度。
  • int inTargetDensity——目標位圖的像素密度。
  • boolean inScaled——設為 true 時進行密度換算,從 inDensity 轉到 inTargetDensity。
  • Config inPreferredConfig——指定解碼時使用的色彩配置,預設 ARGB_8888。

其餘欄位自己查文件即可。


3. 取得 Bitmap 位圖

從資源取得位圖有兩條路:BitmapDrawable 或 BitmapFactory。

方法一:BitmapDrawable

 BitmapDrawable bmpMeizi = new BitmapDrawable(getAssets().open("pic_meizi.jpg"));
 Bitmap mBitmap = bmpMeizi.getBitmap();
 img_bg.setImageBitmap(mBitmap);

方法二:BitmapFactory,全是靜態方法,可以從資源 ID、路徑、檔案、串流等位取得:

 // 從資源 ID
 private Bitmap getBitmapFromResource(Resources res, int resId) {
 return BitmapFactory.decodeResource(res, resId);
 }

 // 從檔案路徑
 private Bitmap getBitmapFromFile(String pathName) {
 return BitmapFactory.decodeFile(pathName);
 }

 // 從位元組陣列
 public Bitmap Bytes2Bimap(byte[] b) {
 if (b.length != 0) {
 return BitmapFactory.decodeByteArray(b, 0, b.length);
 } else {
 return null;
 }
 }

 // 從輸入串流
 private Bitmap getBitmapFromStream(InputStream inputStream) {
 return BitmapFactory.decodeStream(inputStream);
 }

4. 取得 Bitmap 的相關資訊

拿到 Bitmap 物件後,直接呼叫它的方法就好:getByteCount() 取得占用大小,getWidth()/getHeight() 取得尺寸,getConfig() 取得色彩配置。這裡就不重複列了,查文件更快。


5. 把圖片的某一角裁下來

有時候你只想取用圖片的某個區域,直接用 createBitmap() 那個帶座標的重載版本即可,參數依序是:來源 bitmap、起始 x 與 y 座標、要裁的寬與高。

 Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.pic_meizi);
 Bitmap bitmap2 = Bitmap.createBitmap(bitmap1, 100, 100, 200, 200);
 img_bg = (ImageView) findViewById(R.id.img_bg);
 img_bg.setImageBitmap(bitmap2);

執行結果

原圖:

裁下來的一角:

要注意的是,裁切範圍超出原圖邊界會直接丟出例外,正式環境記得先夾住座標。


6. 縮放 Bitmap

這裡先不用 Matrix,直接用 Bitmap 提供的 createScaledBitmap,參數依序是:來源 bitmap、縮放後的寬與高、是否啟用濾波。

最後那個 filter 參數建議設為 true,縮圖時邊緣會平滑一些,代價是稍微多一點運算。


7. 用 Bitmap 做應用內截圖

執行結果

實作程式碼

 public class MainActivity extends AppCompatActivity {

 static ByteArrayOutputStream byteOut = null;
 private Bitmap bitmap = null;
 private Button btn_cut;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 btn_cut = (Button) findViewById(R.id.btn_cut);
 btn_cut.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 captureScreen();
 }
 });
 }

 public void captureScreen() {
 Runnable action = new Runnable() {
 @Override
 public void run() {
 final View contentView = getWindow().getDecorView();
 try {
 Log.e("HEHE", contentView.getHeight() + ":" + contentView.getWidth());
 bitmap = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.ARGB_4444);
 contentView.draw(new Canvas(bitmap));
 ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteOut);
 savePic(bitmap, "sdcard/short.png");
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (null != byteOut) {
 byteOut.close();
 }
 if (null != bitmap && !bitmap.isRecycled()) {
 bitmap = null;
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
 };
 action.run();
 }

 private void savePic(Bitmap b, String strFileName) {
 FileOutputStream fos = null;
 try {
 fos = new FileOutputStream(strFileName);
 if (null != fos) {
 boolean success = b.compress(Bitmap.CompressFormat.PNG, 100, fos);
 fos.flush();
 fos.close();
 if (success) {
 Toast.makeText(MainActivity.this, "截圖成功", Toast.LENGTH_SHORT).show();
 }
 }
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }

程式碼解析

核心只有兩行:getWindow().getDecorView() 取得目前 XML 根節點的 View;接著建立一張同尺寸的 Bitmap,呼叫 contentView.draw(new Canvas(bitmap)) 把畫面畫上去。之後壓縮成串流寫入檔案即可。

從實測結果也可以看出,這種截圖只能拍到「你自己 App 的畫面」。要截整螢幕(含狀態列與其他 App)就必須靠系統 API 或 MediaProjection,那是另一個主題了。


本節小結

本節說明了 Bitmap、BitmapFactory 與其靜態內部類 Options 的關係,示範了 BitmapDrawable 的用法,並實際操作了裁切、縮放與應用內截圖三個常見技巧。

老實說,Bitmap 這層你只要能正確建立與釋放就夠了,更進階的變形與合成通常交給 Matrix 與 Canvas 去處理。真正該花力氣關注的是 OOM 問題——下一節我們就來談怎麼降低 Bitmap 造成 OOM 的風險。

謝謝。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved