一個簡單的照相功能,拍照之後在另一個activit中顯示出拍照的圖片。
首先是佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<SurfaceView
android:id="@+id/sf"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照"></Button>
</LinearLayout>
一個SurfaceView呈現相機拍攝的畫面;
button是點擊後拍照功能;
- 初始化一個SurfaceView 控件;
sf = findViewById(R.id.sf);
sf.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
stop();
}
}
簡單說明一下Surface與SurfaceHolder.Callback之間的聯繫。
Surface是android的一個重要元素,用於android畫面的圖形繪製。而SurfaceView 是視圖(View)的一個繼承類,每一個SurfaceView都內嵌封裝一個Surface。通過調用SurfaceHolder可以調用 SurfaceView,控制圖形的尺寸和大小。而SurfaceHolder 是通過getholder()來取得。創立SurfaceHolder 對象後,用SurfaceHolder.Callback()來回調SurfaceHolder,對SurfaceView進行控制。
surfaceCreated 當Surface第一次創建後會立即調用該函數。程序可以在該函數中做些和繪製界面相關的初始化工作,一般情況下都是在另外的線程來繪製界面,所以不要在這個函數中繪製Surface。
surfaceChanged 當Surface的狀態(大小和格式)發生變化的時候會調用該函數,在surfaceCreated調用後該函數至少會被調用一次。
surfaceDestroyed 當Surface被摧毀前會調用該函數,該函數被調用後就不能繼續使用Surface了,一般在該函數中來清理使用的資源。
創建camera對象,(注意要用import android.hardware.Camera;這個包下的)
public void start() {
camera = Camera.open();
try {
camera.setPreviewDisplay(sf.getHolder());
camera.startPreview();//開始預覽畫面
camera.setDisplayOrientation(90);//拍攝畫面旋轉90度
} catch (IOException e) {
e.printStackTrace();
}
}
把剛纔創建的SurfaceHolder對象設置到camera中;
以上步驟在surfaceCreated()方法中調用;
在界面結束的時候釋放相機資源:
public void stop() {
camera.stopPreview();
camera.release();
}
點擊拍照按鈕之後執行的步驟
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
camera.takePicture(null, null, new Camera.PictureCallback() {//開始拍照;
@Override
public void onPictureTaken(byte[] data, Camera camera) {//拍完之後回調;
String path = null;
if ((path = savephoto(data)) != null) {
Intent in = new Intent(MainActivity.this, MyActivity.class);
in.putExtra("path", path);
startActivity(in);
} else {
Toast.makeText(MainActivity.this, "save photo fail", Toast.LENGTH_LONG).show();
}
}
});
}
});
savephoto()保存當前相片資源到臨時文件中;
private String savephoto(byte[] bytes) {
try {
File f = File.createTempFile("img", "");//前綴,後綴
FileOutputStream fos = new FileOutputStream(f);
fos.write(bytes);
fos.flush();
fos.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
將二進制數據存儲到臨時文件中,並且返回文件路徑;
拍照之後跳轉到另個界面顯示:
package com.example.camera;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import java.io.File;
public class MyActivity extends Activity {
private ImageView iv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
iv=new ImageView(MyActivity.this);
setContentView(iv);
Intent intent =getIntent();
String path=intent.getStringExtra("path");
if (path!=null){
iv.setImageURI(Uri.fromFile(new File(path)));
}
}
}
iv.setImageURI(Uri.fromFile(new File(path)));通過文件路徑,創建一個文件;
主activity的代碼如下:
package com.example.camera;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private SurfaceView sf;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
camera.takePicture(null, null, new Camera.PictureCallback() {//開始拍照;
@Override
public void onPictureTaken(byte[] data, Camera camera) {//拍完之後回調;
String path = null;
if ((path = savephoto(data)) != null) {
Intent in = new Intent(MainActivity.this, MyActivity.class);
in.putExtra("path", path);
startActivity(in);
} else {
Toast.makeText(MainActivity.this, "save photo fail", Toast.LENGTH_LONG).show();
}
}
});
}
});
sf = findViewById(R.id.sf);
sf.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
stop();
}
});
}
private String savephoto(byte[] bytes) {
try {
File f = File.createTempFile("img", "");//前綴,後綴
FileOutputStream fos = new FileOutputStream(f);
fos.write(bytes);
fos.flush();
fos.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void start() {
camera = Camera.open();
try {
camera.setPreviewDisplay(sf.getHolder());
camera.startPreview();//開始預覽畫面
camera.setDisplayOrientation(90);//拍攝畫面旋轉90度
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
camera.stopPreview();
camera.release();
}
}
記得需要添加照相機權限:
<uses-permission android:name="android.permission.CAMERA"></uses-permission>