Platform: RK3288
OS: Android 6.0
Kernel: 3.10.92
说明:
1.打开就预览
2. button用于控制是开启preview callback并保存为jpg
源代码:
package com.example.camerapreviewtest;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ContentFrameLayout;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Camera mCamera;
private CameraPreview mPreview;
SurfaceHolder mSurfaceHolder;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
Log.i(TAG, "camera number: "+Camera.getNumberOfCameras());
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick: ");
mCamera.setPreviewCallback(new Camera.PreviewCallback(){
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Size size = mCamera.getParameters().getPreviewSize();
try{
YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
if(image!=null){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, size.width, size.height), 80 ,stream);
FileOutputStream output = new FileOutputStream("/sdcard/t.jpg");
output.write(stream.toByteArray());
output.flush();
output.close();
Log.i(TAG, "onPreviewFrame: to jpeg");
}
} catch (Exception e){
}
}
});
}
}
);
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
if(c==null)
Log.i(TAG, "getCameraInstance: ");
}catch (Exception e){
Log.i(TAG, "getCameraInstance: exception");
}
return c;
}
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera){
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
}
public void surfaceCreated(SurfaceHolder holder){
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch (IOException e){
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(mCamera!=null){
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
}
原作者:KrisFei
|