編輯:關於 Android 程式設計
相機在手機裡的地位舉足輕重: QR Code 掃描、拍照辨識、影像記錄,樣樣離不開它。本文從最基礎的調用方式講起,一路走到自訂 Camera。
權限先行:
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-feature android:name="android.hardware.camera" />
透過系統定義的 Intent Action,就能直接叫起任何實作 Camera 功能的 App,成本最低。
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
用 startActivityForResult 叫起,並在 onActivityResult 中接收結果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
mImageViewShow.setImageBitmap(bitmap);
}
但這裡有個坑:手機像素越來越高,這張圖會有多大?會不會因為 Bundle 太大而 FC?Android 早就想過了——data 裡放的根本不是原圖,而是一張縮圖。所以想拿到完整解析度的照片,就不能走這條路。
正確做法是透過 EXTRA_OUTPUT 指定輸出路徑,相當於先開一個暫存檔:
String tempPath = Environment.getExternalStorageDirectory().getPath(); mFilePath = tempPath + "/" + "test1.png"; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri photoUri = Uri.fromFile(new File(mFilePath)); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); startActivityForResult(intent, CAMERA_CODE1);
回來時不讀 data,直接讀檔案:
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = new FileInputStream(mFilePath);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
這樣才能拿到完整原圖。後續要顯示時,仍需處理大圖的取樣問題以避免 OutOfMemoryError,這部分不在本文範圍。
如果你的需求真的只是「拍張照帶走」,系統 Intent 已經足夠。但多數情況並非如此,所以下面看自訂 Camera。
依據官方文件,自訂相機大致需要這幾步:
一步一步來。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="horizontal">
<Button
android:id="@+id/btn_switch_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:onClick="switchCamera"
android:text="切換攝影頭" />
<Button
android:id="@+id/btn_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:onClick="capture"
android:text="拍照" />
</LinearLayout>
<SurfaceView
android:id="@+id/sv_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ll" />
</RelativeLayout>
兩個按鈕加一個 SurfaceView,非常直觀:

開啟時務必包 try-catch,因為 Camera.open() 在裝置被其他 App 佔用時會拋出例外:
private Camera getCamera() {
Camera camera;
try {
camera = Camera.open();
} catch (Exception e) {
camera = null;
}
return camera;
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private void setStartPreview(Camera camera, SurfaceHolder holder) {
try {
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
PS:
setDisplayOrientation(90)這行不能省。不設方向的話預設是橫向,畫面會歪得莫名其妙。即使設了 90 度,畫面比例也可能不對——那是因為你沒有對預覽尺寸做正確的縮放。
mCamera.takePicture(null, null, mPictureCallback);
拍照前先設定參數:
Camera.Parameters params = mCamera.getParameters();
params.setPictureFormat(ImageFormat.JPEG);
params.setPreviewSize(800, 400);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(params);
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
mCamera.takePicture(null, null, mPictureCallback);
}
});
以及結果回呼:
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Intent intent = new Intent(CustomCamera.this, CameraResult.class);
intent.putExtra("picPath", pictureFile.getAbsolutePath());
startActivity(intent);
CustomCamera.this.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
};
回呼裡把檔案路徑丟給展示用的 Activity,相機的拍攝與呈現就完整串起來了。
SurfaceView 設成 match_parent,預覽畫面幾乎一定會被拉伸。解法是動態調整 SurfaceView 的尺寸去適配相鄰區域。官方 ApiDemos 裡就有現成範例:
android-22/legacy/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.java
一句話總結:內事不懂看源碼,外事不懂看 Demo。
聽起來很進階,實際上只要用 FrameLayout 把 SurfaceView 包起來,然後想加什麼就加什麼:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ll">
<SurfaceView
android:id="@+id/sv_camera"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
android:src="@drawable/demo" />
</FrameLayout>
不只是 ImageView,換成 ViewPager 也行——甚至可以做成可切換的水印相機。加上去的一切都能操作,動效、顏色,都是分鐘級的事。

以上。起步之後,我們就要開始跑了。
本文寫於 Camera1 API 的年代。在 Android 6.0 之後,CAMERA 屬於執行期危險權限,必須動態向使用者請求;Android 9 起還限制了後台存取相機。若要在新專案中使用,建議直接採用 CameraX,它已把預覽、拍照、影像分析以及方向與比例問題都封裝好了,能省下大量上述手動處理的功夫。讀懂 Camera1 的運作原理仍有價值,但不必再從零打造。
Android ListView 字母排序:實現字母擠壓、右側快速定位與關鍵字搜索
本文將講解如何自定義 EditText 實現搜索框的自定義樣式,以及字母擠壓效果的實現思路,並最終完成一個具備字母排序、右側快速選取與關鍵字搜索功能的通訊錄列表。 自定義
從源碼看 Android 中的適配器模式
在 Android 開發中,ListView 的 Adapter 可說是最常見的型別之一。我們需要透過 Adapter 載入 Item View 的布局,並完成資料綁定、
一分鐘上手樂視雲直播Demo集成
為什麼選擇第三方直播SDK如果從零實現直播功能,需要處理推流協議、編碼、服務器並發、負載均衡、播放器延時與兼容性等大量問題。對於大多數業務團隊而言,集成成熟的第三方直播S
徹底搞懂 Android 的 layout_weight:剩餘空間到底是怎麼分的
寫 Demo 時碰到 layout_weight,網上關於它的討論很多,但多數說法流於口訣——「值越小權重越大」這類結論背誦起來容易,遇到實際問題就完全用不上。我自己把資