Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 技術精髓:Bitmap 圖像處理詳解

編輯:關於 Android 程式設計

Bitmap(android.graphics.Bitmap)是 Android 系統中最重要的圖像處理類之一。借助它,你可以讀取圖像文件信息,進行剪切、旋轉、縮放等操作,並按指定格式保存圖像。本篇系統梳理它的常用 API 與典型用法。

Bitmap 核心方法

public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream):把位圖壓縮寫入指定的 OutputStream。format 指定壓縮格式,quality 取值 0-100(0 為最小尺寸壓縮,100 為最高質量;PNG 是無損格式,會忽略此參數)。返回是否壓縮成功。

public void recycle():回收位圖占用的內存,並把位圖標記為 Dead。

public final boolean isRecycled():判斷位圖內存是否已釋放。

getWidth() / getHeight():獲取位圖的寬與高。

public final boolean isMutable():判斷圖片是否可修改。

createBitmap 系列靜態方法:可以以原圖為基礎創建新圖像,指定新圖的高寬、是否縮放、起始坐標等,是圖像變換的核心工具。

BitmapFactory 工廠類

Options 參數類中幾個關鍵字段:

inJustDecodeBounds:設為 true 時不真正加載圖片、不分配內存,只返回圖片的寬高信息。

inSampleSize:圖片縮放倍數,設為 4 則寬高都變為原來的 1/4,面積變為 1/16。

outWidth / outHeight:獲取圖片的實際寬高。

常用解碼方法包括 decodeFile(從文件路徑解碼)、decodeResource(從資源解碼)、decodeStream(從輸入流解碼)、decodeByteArray(從字節數組解碼)等,涵蓋了各種數據來源。

使用 BitmapFactory 解碼資源

ImageView imgView = (ImageView)findViewById(R.id.image3); imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon));

捕獲並保存位圖

public void captureImage(View view) { Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, 0); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode==0 && resultCode==Activity.RESULT_OK) { Bitmap myBitmap = (Bitmap) data.getExtras().get("data"); } }

縮放與采樣(避免內存溢出)

加載大圖時,常用「先取邊界、再按 inSampleSize 縮放」的兩段式做法,能有效降低內存占用:

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions); bmpFactoryOptions.inSampleSize = 2; bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions); imv.setImageBitmap(bmp);

在 Canvas 上繪制位圖

Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig()); Canvas canvas = new Canvas(alteredBitmap); Paint paint = new Paint(); canvas.drawBitmap(bmp, 0, 0, paint);

用 Matrix 做圖像變換

Matrix matrix = new Matrix(); matrix.setValues(new float[] { 1, .5f, 0, 0, 1, 0, 0, 0, 1 }); canvas.drawBitmap(bmp, matrix, paint);

總結

1. 獲取位圖:可用 BitmapDrawable 或 BitmapFactory。BitmapFactory 的所有方法都是 static,支持通過資源 ID、路徑、文件、數據流等多種方式獲取。Android SDK 推薦的格式依次為 png(首選)、jpg(可接受)、gif(不推薦)。

2. 獲取位圖信息:位圖大小、是否含透明度、顏色格式等都能從 Bitmap 對象輕松獲取。顏色格式由 Bitmap.Config 定義,包含 ALPHA_8、ARGB_4444、ARGB_8888、RGB_565。

3. 顯示位圖:可借助 BitmapDrawable 顯示到 ImageView,也可用 Canvas 的 drawBitmap 繪製。

4. 縮放:可通過 createBitmap 配合 Matrix、Canvas.scale 或 drawBitmap 的 src/dst 矩形實現。

5. 旋轉:借助 Matrix.setRotate 或 createBitmap 帶 Matrix 參數的版本實現。

掌握這些 API,日常的圖片加載、變換與保存需求基本都能應對自如。

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