編輯:關於 Android 程式設計
查了一圈資料並實際動手之後,圖片壓縮大致可以分成兩類:質量壓縮(不改變圖片尺寸)與尺寸壓縮(本質上是像素級的壓縮)。質量壓縮常用於上傳大圖前先減量,節省流量——畢竟現在手機隨手一拍就有 3M;尺寸壓縮則常用於生成縮圖。
兩種我都實裝進了專案,卻發現一件怪事:一張 1.9M 的圖片做質量壓縮之後,反而變成 3M 多。進一步追查才找到原因。
1. 檔案形式(以二進位存在硬盤上)
2. 串流形式(以二進位存在記憶體中)
3. Bitmap 形式
前兩者對「體積」的認知是一致的:SD 卡上 100K 的圖,讀進記憶體仍是 100K。但一旦變成 Bitmap,佔用記憶體會瞬間暴增——我試過 500K 的檔案轉成 Bitmap 後佔了近 10M,這個倍數並非固定,取決於解析度與像素格式。
三種形式的大小量法:
檔案形式:file.length()
串流形式:讀進 ByteArrayInputStream 後看 byte 數
Bitmap:bitmap.getByteCount()
所謂的質量壓縮,其實只對「檔案形式」生效。你可以把 file 轉成 bitmap 再轉回 file,最終那個 file 確實變小了,但中間的 bitmap 幾乎沒被壓縮——因為 bitmap 在記憶體中的大小是按像素算的(width × height),而質量壓縮並不改變像素。所以壓縮後寫成檔案變小了,重新讀成 Bitmap 時佔的記憶體卻沒少。這也解釋了為什麼會出現「越壓越大」:若原始檔案本身已是高壓縮率的 JPEG,重新編碼反而可能變大。
而尺寸壓縮直接削減像素,對 bitmap 產生實質影響,最終檔案自然也跟著變小。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
/**
* Image compress factory class
*/
public class ImageFactory {
/**
* 依路徑讀出 bitmap
*/
public Bitmap getBitmap(String imgPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;
newOpts.inPurgeable = true;
newOpts.inInputShareable = true;
newOpts.inSampleSize = 1;
newOpts.inPreferredConfig = Config.RGB_565;
return BitmapFactory.decodeFile(imgPath, newOpts);
}
/**
* 把 bitmap 存成檔案
*/
public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
FileOutputStream os = new FileOutputStream(outPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
/**
* 依尺寸壓縮(會改變寬高),常用於縮圖
*/
public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 先只讀邊不讀內容
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = pixelH;
float ww = pixelW;
// 固定比例縮放,用寬或高中的一個計算即可
int be = 1; // be=1 表示不縮放
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;
bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
// 這裡再做質量壓縮意義不大反而耗資源,故移除
return bitmap;
}
/**
* 依尺寸壓縮 bitmap 物件
*/
public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
if (os.toByteArray().length / 1024 > 1024) {
// 大於 1M 先壓一次,避免後續 decodeStream 時溢出
os.reset();
image.compress(Bitmap.CompressFormat.JPEG, 50, os);
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = pixelH;
float ww = pixelW;
int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;
is = new ByteArrayInputStream(os.toByteArray());
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
return bitmap;
}
/**
* 質量壓縮並輸出檔案
*/
public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
int options = 100;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// 迴圈降級直到小於目標
while (os.toByteArray().length / 1024 > maxSize) {
os.reset();
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
fos.flush();
fos.close();
}
/**
* 質量壓縮並輸出檔案(可選擇刪除原檔)
*/
public void compressAndGenImage(String imgPath, String outPath, int maxSize,
boolean needsDelete) throws IOException {
compressAndGenImage(getBitmap(imgPath), outPath, maxSize);
if (needsDelete) {
File file = new File(imgPath);
if (file.exists()) {
file.delete();
}
}
}
/**
* 尺寸縮放並輸出縮圖
*/
public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH)
throws FileNotFoundException {
Bitmap bitmap = ratio(image, pixelW, pixelH);
storeImage(bitmap, outPath);
}
public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH,
boolean needsDelete) throws FileNotFoundException {
Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
storeImage(bitmap, outPath);
if (needsDelete) {
File file = new File(imgPath);
if (file.exists()) {
file.delete();
}
}
}
}
1. 存成本地檔案時壓縮(Bitmap → File)
特點:檔案形式確實被壓縮了,但重新讀成 Bitmap 時佔用的記憶體並未改變。
這個方法壓的是「質量」,不減少像素。比方說一張 300K、1280×700 的圖,壓完檔案也許掉到 100K 以下方便上傳,但 BitmapFactory.decodeFile() 之後像素仍是 1280×700。
public static void compressBmpToFile(Bitmap bmp, File file) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 80; // 從 80 開始
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
官方文件也說明它會重建圖片,且位深與每個像素的透明度可能改變;JPEG 只支援不透明,因此原圖中透明的部分會消失,這種格式確實可能造成失真。既然它改變的是顯示質量、像素沒變,重新讀成 Bitmap 時記憶體佔用自然不會減少——bitmap.getByteCount() 算的正是像素所需記憶體。
2. 從本地讀進記憶體時壓縮(File → Bitmap)
特點:透過設定 inSampleSize 減少像素,真正壓到記憶體中的 Bitmap。
先看這個方法:
private Bitmap compressBmpFromBmp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
return BitmapFactory.decodeStream(isBm, null, null);
}
依前面的理論,這個對記憶體中 Bitmap 做質量壓縮的寫法其實是無效且多餘的——你已經把它讀進記憶體了,此時再壓一次意義不大。
再看真正有效的寫法:
private Bitmap compressImageFromFile(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true; // 只讀邊不讀內容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;
float ww = 480f;
int be = 1;
if (w > h && w > ww) {
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be; // 設定采樣率
newOpts.inPreferredConfig = Config.ARGB_8888; // 預設值,可不設
newOpts.inPurgeable = true; // 需與下一行同時設定才有效
newOpts.inInputShareable = true; // 記憶體不足時圖片可被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
// return compressBmpFromBmp(bitmap); // 二次壓縮無效,已移除
return bitmap;
}
補充:按尺寸壓縮並輸出
public static void compressPicture(String srcPath, String desPath) {
FileOutputStream fos = null;
BitmapFactory.Options op = new BitmapFactory.Options();
// 先只讀邊
op.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
op.inJustDecodeBounds = false;
float w = op.outWidth;
float h = op.outHeight;
float hh = 1024f; // 最長邊限制 1024
float ww = 1024f;
float be = 0f;
if (w > h && w > ww) {
be = (float) (w / ww);
} else if (w < h && h > hh) {
be = (float) (h / hh);
}
if (be <= 0) {
be = 0f;
}
op.inSampleSize = (int) be; // 數字越大,圖越小
bitmap = BitmapFactory.decodeFile(srcPath, op);
int desWidth = (int) (w / be);
int desHeight = (int) (h / be);
bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
try {
fos = new FileOutputStream(desPath);
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
一句話總結選型:要上傳就壓質量、要顯示縮圖就壓尺寸。另外別忘了 inSampleSize 只接受整數,若目標縮放比介於 1 到 2 之間,它會被取捨成 1 而失去效果,這種情況得改用 createScaledBitmap() 或矩陣縮放來處理。
別再手動拼字串:用 XmlSerializer 安全產生 Android 備份 XML
早期做短信備份時,XML 是用字串拼接硬做出來的。這種寫法在資料「乾淨」時勉強能用,但只要短信內容裡出現 <、>、& 這類字元,產生的檔案立刻不再是合
Android 專案建立與目錄結構圖解:一次看懂 Eclipse 專案組成
建立 Android 專案在 Eclipse 中建立 Android 專案時,通常會選擇 Android Application Project,接著依序設定專案名稱、套
Android 系統之路(初識 MTK):修改首次開機默認亮度、日期格式與機型屬性
今天給大家分享一些 MTK 平台下的系統定製技巧:修改系統首次開機的默認屏幕背光亮度、在系統語言為英語時調整默認日期格式,以及修改拍照相關的機型屬性。如果對具體修改位置不
MVP 架構實踐:從原理到可運行的天氣 Demo
做 Android 久了,幾乎每個人都遇過同一個問題:Activity 或 Fragment 的檔案越寫越肥,兩三千行下來,_findView、業務邏輯、網路請求、動畫全