編輯:關於 Android 開發
用 ACTION_IMAGE_CAPTURE 拍照後直接把 bitmap 塞進 ImageView,在解析度高的手機上幾乎必然 OOM——一張 1200 萬畫素的照片解碼後要吃掉將近 50MB 記憶體。正確做法分兩步:先只讀取尺寸資訊,再按目標大小降採樣解碼。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo" />
<Button
android:id="@+id/get_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Photo" />
<ImageView
android:id="@+id/picture"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
package com.example.choosepictest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
static final int REQUEST_IMAGE_CAPTURE = 1;
private Button takePhoto;
private Button getPhoto;
private ImageView picture;
private Uri imgUri;
private String mCurrentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto = (Button) findViewById(R.id.take_photo);
getPhoto = (Button) findViewById(R.id.get_photo);
picture = (ImageView) findViewById(R.id.picture);
takePhoto.setOnClickListener(this);
getPhoto.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_photo:
dispatchTakePictureIntent();
break;
default:
break;
}
}
/** 啟動相機,並指定輸出去處以取得全尺寸照片 */
private void dispatchTakePictureIntent() {
File appDir = new File(Environment.getExternalStorageDirectory(), "/etoury/picCache");
if (!appDir.exists()) {
appDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File outputImage = new File(appDir, timeStamp + ".jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
mCurrentPhotoPath = outputImage.getAbsolutePath();
imgUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// 關鍵:指定輸出的 Uri,相機就會把完整解析度的照片寫到這裡
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
/** 降採樣解碼:避免記憶體溢出 */
private void setPic() {
int targetW = picture.getWidth();
int targetH = picture.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// 設為 true 時只讀取邊界資訊,不真正解碼、不配置像素記憶體
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// 取兩軸中較小的縮放倍數,確保縮完後仍大於目標尺寸
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
bmOptions.inJustDecodeBounds = false;
// 恰當的 inSampleSize 能讓 BitmapFactory 配置更少記憶體
bmOptions.inSampleSize = scaleFactor;
// 記憶體吃緊時允許回收像素區
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
picture.setImageBitmap(bitmap);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
galleryAddPic();
setPic();
break;
default:
break;
}
}
}
/** 發送掃描通知,讓照片立刻出現在相簿裡 */
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imgUri);
this.sendBroadcast(mediaScanIntent);
}
}
inSampleSize 只接受 2 的次方以外的值也能運作,但會向下取整。若 scaleFactor 算出來是 3,實際會用 2;想要精準控制就自己寫 while 迴圈把它湊成 2 的次方。
targetW/targetH 可能為 0。如果在版面尚未量測完成時就呼叫 setPic(),ImageView 的寬高會是 0,導致除零或縮放倍數異常。實務上可用 ViewTreeObserver 或 post() 等到量測完成再解碼。
記得檢查權限與目錄。Android 6.0 之後寫入外部儲存需要動態申請 WRITE_EXTERNAL_STORAGE;Android 10 以上更建議改用 MediaStore 或 app 專屬目錄 getExternalFilesDir(),避免被限定儲存空間政策攔下。
Android 自定義 View 實現帶數字進度條
NumberProgressBar 簡介NumberProgressBar 是在 ProgressBar 基礎上加入數字顯示與自定義樣式的控制項。它可分成已達成區域、文字
Android 手機衛士 16——動手實作手機殺毒掃描功能
從旋轉動畫到病毒比對:一支完整的掃描流程 殺毒頁面的視覺重點,是那個不停轉動的掃描圖標;而真正的重頭戲,則是背後「取特徵碼 → 比對病毒庫 → 回報結果」的一整套邏輯。
FFmpeg 使用手冊:FFmpeg 的基本組成與工作流程
FFmpeg 的基本組成 FFmpeg 是一個強大的音視頻處理工具集,涵蓋封裝、解封裝、編碼、解碼、濾鏡、縮放、採集與播放等多種能力。理解其模塊劃分,有助於更好地使用命令
深入剖析二層(鏈路層)資料包的發送過程(Linux 2.6.32 內核)
二層(鏈路層)資料包發送過程分析 說明:本系列博文所涉及的內核版本為 2.6.32。 當上層準備好一個封包並交給鏈路層後,鏈路層的發送主要由 dev_queue_xmit