編輯:Android 開發實例
Bitmap 是 Android 圖片處理的核心類,項目裡幾乎繞不開它。本文把日常開發中最常用的幾類操作整理在一起:生成圓角圖片、生成縮略圖、對圖片尺寸與體積進行壓縮,以及從 SD 卡讀取圖片。代碼裡每一步都做了註釋,方便查閱。
注意:測試其中某一個方法時,最好把其餘相關代碼註釋掉,避免相互干擾。
package com.testbitmapscale;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;
// 方法:
// 1 生成圓角 Bitmap 圖片
// 2 生成 Bitmap 縮略圖
// 3 壓縮圖片的長寬以及 kB
public class MainActivity extends Activity {
private ImageView imageView;
private Bitmap copyRawBitmap1;
private Bitmap copyRawBitmap2;
private Bitmap copyRawBitmap3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.imageView);
// 第一種方式: 從資源文件中得到圖片
Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.haha);
copyRawBitmap1 = rawBitmap;
copyRawBitmap2 = rawBitmap;
copyRawBitmap3 = rawBitmap;
// 第二種方式: 從 SD 卡中得到圖片(方法1)
String SDCardPath = Environment.getExternalStorageDirectory().toString();
String filePath = SDCardPath + "/" + "haha.jpg";
Bitmap rawBitmap1 = BitmapFactory.decodeFile(filePath, null);
// 第二種方式: 從 SD 卡中得到圖片(方法2)
InputStream inputStream = getBitmapInputStreamFromSDCard("haha.jpg");
Bitmap rawBitmap2 = BitmapFactory.decodeStream(inputStream);
// ----> 以下為將圖片設置圓角
Bitmap roundCornerBitmap = this.toRoundCorner(rawBitmap, 40);
imageView.setImageBitmap(roundCornerBitmap);
// ----> 以上為將圖片設置圓角
// ----> 以下為將圖片高寬和大小(kB)壓縮
int rawHeight = rawBitmap.getHeight();
int rawWidth = rawBitmap.getWidth();
int newHeight = 500;
int newWidth = 500;
float heightScale = ((float) newHeight) / rawHeight;
float widthScale = ((float) newWidth) / rawWidth;
Matrix matrix = new Matrix();
matrix.postScale(heightScale, widthScale);
// matrix.postRotate(-30); // 設置旋轉角度
// matrix.postSkew(0.1f, 0.1f); // 設置傾斜
Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true);
Drawable newBitmapDrawable = new BitmapDrawable(newBitmap);
imageView.setImageDrawable(newBitmapDrawable);
this.compressAndSaveBitmapToSDCard(newBitmap, "xx100.jpg", 80);
// 問題: 原圖 625x690 90.2kB,設為 500x500 壓縮後反而變成 171kB。
// 原因是 compress() 的 quality 參數設得太大(如 100),常用 80 即可。
// ----> 以上為將圖片高寬和大小(kB)壓縮
// ----> 以下為將圖片的 kB 壓縮,寬高不變
this.compressAndSaveBitmapToSDCard(copyRawBitmap1, "0011fa.jpg", 80);
// ----> 以上為將圖片的 kB 壓縮,寬高不變
// ----> 以下為獲取 SD 卡圖片的縮略圖方法1
String SDCardPath1 = Environment.getExternalStorageDirectory().toString();
String filePath1 = SDCardPath1 + "/" + "haha.jpg";
Bitmap bitmapThumbnail1 = this.getBitmapThumbnail(filePath1);
imageView.setImageBitmap(bitmapThumbnail1);
// ----> 以上為獲取 SD 卡圖片的縮略圖方法1
// ----> 以下為獲取 SD 卡圖片的縮略圖方法2
String SDCardPath2 = Environment.getExternalStorageDirectory().toString();
String filePath2 = SDCardPath2 + "/" + "haha.jpg";
Bitmap tempBitmap = BitmapFactory.decodeFile(filePath2);
Bitmap bitmapThumbnail2 = ThumbnailUtils.extractThumbnail(tempBitmap, 100, 100);
imageView.setImageBitmap(bitmapThumbnail2);
// ----> 以上為獲取 SD 卡圖片的縮略圖方法2
}
// 讀取 SD 卡下的圖片
private InputStream getBitmapInputStreamFromSDCard(String fileName) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String SDCardPath = Environment.getExternalStorageDirectory().toString();
String filePath = SDCardPath + File.separator + fileName;
File file = new File(filePath);
try {
FileInputStream fileInputStream = new FileInputStream(file);
return fileInputStream;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
// 獲取 SDCard 的目錄路徑
private String getSDCardPath() {
String SDCardPath = null;
boolean IsSDcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (IsSDcardExist) {
SDCardPath = Environment.getExternalStorageDirectory().toString();
}
return SDCardPath;
}
// 壓縮且保存圖片到 SDCard
private void compressAndSaveBitmapToSDCard(Bitmap rawBitmap, String fileName, int quality) {
String saveFilePaht = this.getSDCardPath() + File.separator + fileName;
File saveFile = new File(saveFilePaht);
if (!saveFile.exists()) {
try {
saveFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
if (fileOutputStream != null) {
// compress(format, quality, stream)
// quality 為 0-100,0 意味著小尺寸壓縮,100 意味著高質量壓縮
rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 獲取圖片的縮略圖(通過 inSampleSize 進行降採樣)
private Bitmap getBitmapThumbnail(String filePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 只解析邊界信息,不分配內存
Bitmap rawBitmap = BitmapFactory.decodeFile(filePath, options);
// inSampleSize 表示縮略圖為原圖的幾分之一
int sampleSize = computeSampleSize(options, 150, 200 * 200);
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize;
Bitmap thumbnailBitmap = BitmapFactory.decodeFile(filePath, options);
this.compressAndSaveBitmapToSDCard(thumbnailBitmap, "15.jpg", 80);
return thumbnailBitmap;
}
// 計算 sampleSize
public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
/**
* @param bitmap 需要修改的圖片
* @param pixels 圓角的弧度
* @return 圓角圖片
*/
public Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(roundCornerBitmap);
int color = 0xff424242;
Paint paint = new Paint();
paint.setColor(color);
paint.setAntiAlias(true); // 防止鋸齒
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
RectF rectF = new RectF(rect);
float roundPx = pixels;
canvas.drawARGB(0, 0, 0, 0); // 相當於清屏
canvas.drawRoundRect(rectF, roundPx, roundPx, paint); // 先畫一個帶圓角的矩形
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint); // 再把原圖片畫上去
return roundCornerBitmap;
}
}幾個實用要點總結一下:圓角是通過「先畫圓角矩形、再用 SRC_IN 混合模式把原圖貼上去」實現的;縮略圖的關鍵在 inSampleSize 降採樣,能在解碼階段就大幅降低內存佔用,比先加載再縮放聰明得多;而壓縮時 quality 參數別盲目設 100,80 往往就能兼顧清晰度與體積。掌握這幾招,日常圖片處理基本夠用了。
Android 進階:手機與 BLE 終端通信實戰
近來可穿戴設備發展火熱,也帶旺了相關技術,其中一項便是 BLE(Bluetooth Low Energy,低功耗藍牙)。BLE 是藍牙 4.0 的核心 Profile,主
Android JSON 解析入門:用 JSONObject 把 API 資料讀進 App
JSON 的全名是 JavaScript Object Notation。它其實和 JavaScript 沒有綁定關係,而是一套獨立、輕量、人類也讀得懂的資料交換格式。在
Android 多語系支援:本地化字串資源的建立與切換實測
你的 App 可能同時被東京、羅馬、墨西哥城的使用者打開。要讓每個人都讀得懂,靠的不是在程式碼裡寫一堆 if 判斷,而是把文字交給資源系統,讓它依裝置語言自動挑選合適的版
Android APK 反編譯到 Java 源碼解析
Android 的 APK 內包含編譯後的 classes.dex,因此在一定條件下可被反編譯研究。本文整理常見流程,涵蓋 dex 轉 jar、jar 反編譯 Java