Categories
程式設計 資訊科學

在 Android 中做縮圖

剛好試出來,所以記下來備查。
在 Android 程式中常會使用 Bitmap 這個 class 來處理圖片,不過它並沒有直接提供我想要的縮圖 method(如:resize(w, h)之類的),所以我就試出了以下這段程式碼:

// filePath 是原圖的路徑
Bitmap originalBitmap = BitmapFactory.decodeFile(filePath);
int width = originalBitmap.getWidth();
int height = originalBitmap.getHeight();
// 經過一番激烈地運算後求出
float scaledWidth = ...;
// 及
float scaledHeight = ...;
// 設定 transform matrix
Matrix scaleMatrix = new Matrix();
scaleMatrix.postScale(scaledWidth, scaledHeight);
// 產生縮圖後的 bitmap
Bitmap resizedBitmap =
Bitmap.createBitmap(originalBitmap, 0, 0, width, height, scaleMatrix, true);
// 壓成 JPEG 存檔
FileOutputStream fos = new FileOutputStream("/path/to/newImage.jpg");
resizedBitmap.compress(CompressFormat.JPEG, 100, fos);
fos.close();

別忘了處理 exceptions 就好了 😛

7 replies on “在 Android 中做縮圖”

請問eric大師,你的方法跟下面這個Bitmap的API哪個比較省記憶體?
createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

This is a good tour guide for Android developers. Yet I have some comment for Bitmap operations. First, remember to catch “OutOfMemoryError” exception when decoding any image, develops should know how GC works in dalvik VM. Also mind that decoding and createScaledBitmap() operations are expansive, I recommend to assign Bitmap.inTempStorage to enhance any processing in Bitmap.

Leave a Reply

Your email address will not be published. Required fields are marked *