這個 Demo 實現的效果很直接:調用手機上已安裝的相機拍照,拍完把照片用 ImageView 展示出來。學習重點有兩個——如何拉起系統相機,以及如何避免大圖把內存撐爆,主要涉及 BitmapFactory 與 BitmapFactory.Options。
加載並顯示一張圖對內存占用的影響非常顯著。Android 提供了 BitmapFactory 這個工具類,以一系列靜態方法支持從各種來源載入 Bitmap。我們的需求是從文件加載,而這些方法都會接受 BitmapFactory.Options 參數,從而能控制「怎樣把 Bitmap 讀進內存」。
關鍵在 inSampleSize:設為 8,得到的圖尺寸就是原圖的 1/8。而取樣值的計算有個技巧——先把 inJustDecodeBounds 置為 true,此時 BitmapFactory 只返回圖像的範圍信息(outWidth、outHeight),並不解碼像素本身;拿到尺寸算出合適的比率後,再把 inJustDecodeBounds 設回 false,做真正的解碼。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
package com.multimediademo1;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.widget.ImageView;
public class MainActivity extends Activity {
private final static int CAMERA_RESULT = 0;
private ImageView imageView;
private String imageFilePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageFilePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/myfavoritepicture.jpg";
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(intent, CAMERA_RESULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
imageView = (ImageView) findViewById(R.id.imageView);
Display currentDisplay = getWindowManager().getDefaultDisplay();
int dw = currentDisplay.getWidth();
int dh = currentDisplay.getHeight();
// 第一次只讀取尺寸,不解碼圖像本身
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFilePath, options);
int heightRatio = (int) Math.ceil(options.outHeight / (float) dh);
int widthRatio = (int) Math.ceil(options.outWidth / (float) dw);
// 兩個比率都大於 1,說明圖像至少有一條邊超出屏幕
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
options.inSampleSize = heightRatio;
} else {
options.inSampleSize = widthRatio;
}
}
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath, options);
imageView.setImageBitmap(bitmap);
}
}
}
實戰補充:4.4 以後寫入外部存儲需要 WRITE_EXTERNAL_STORAGE 權限,7.0 起 Uri.fromFile 會觸發 FileUriExposed 異常,需改用 FileProvider;示例中的 getWidth() 等 API 也已在新版本中廢棄。思路不變,替換成新 API 即可。