如何在android中使用surfaceview类捕获图像后在imageview中显示图像
我有使用自定义摄像头API捕获图像的代码,问题是它没有返回到预览模式,主要问题是我想在imageview中显示捕获的图像“ 这是我的代码: CameraPreview.java如何在android中使用surfaceview类捕获图像后在imageview中显示图像,android,android-camera,Android,Android Camera,我有使用自定义摄像头API捕获图像的代码,问题是它没有返回到预览模式,主要问题是我想在imageview中显示捕获的图像“ 这是我的代码: CameraPreview.java import java.io.IOException; import android.content.Context; import android.hardware.Camera; import android.hardware.Camera.AutoFocusMoveCallback; import android.
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusMoveCallback;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
Camera.Parameters prams = mCamera.getParameters();
prams.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(prams);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.autoFocus(null);
} catch (IOException e) {
// left blank for now
}
}@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
MainActivity.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private Camera mCamera;
private CameraPreview mCameraPreview;
private Button captureButton;
private ImageView showImageView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
ImageView showImageView = (ImageView) findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new 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();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
活动\u main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_above="@+id/btns"
android:layout_alignParentTop="true" >
</FrameLayout>
<RelativeLayout
android:id="@+id/btns"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#ccc" >
<Button
android:id="@+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:background="@drawable/btn_white" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="22dp"
android:src="@drawable/backeff" />
</RelativeLayout>
</RelativeLayout>
您好,请尝试下面的代码
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private Button captureButton;
private ImageView showImageView;
protected String imageFilePath;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_view);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
showImageView = (ImageView) findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, jpegCallback);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
/** The jpeg callback. */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
File miDirs = new File(
Environment.getExternalStorageDirectory() + "/myphotos");
if (!miDirs.exists())
miDirs.mkdirs();
final Calendar c = Calendar.getInstance();
String new_Date = c.get(Calendar.DAY_OF_MONTH) + "-"
+ ((c.get(Calendar.MONTH)) + 1) + "-"
+ c.get(Calendar.YEAR) + " " + c.get(Calendar.HOUR)
+ "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
imageFilePath = String.format(
Environment.getExternalStorageDirectory() + "/myphotos"
+ "/%s.jpg", "te1t(" + new_Date + ")");
Uri selectedImage = Uri.parse(imageFilePath);
File file = new File(imageFilePath);
String path = file.getAbsolutePath();
Bitmap bitmap = null;
outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
if (path != null) {
if (path.startsWith("content")) {
bitmap = decodeStrem(file, selectedImage,
CameraActivity.this);
} else {
bitmap = decodeFile(file, 10);
}
}
if (bitmap != null) {
showImageView.setImageBitmap(bitmap);
Toast.makeText(CameraActivity.this,
"Picture Captured Successfully:", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(CameraActivity.this,
"Failed to Capture the picture. kindly Try Again:",
Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
};
/**
* Decode strem.
*
* @param fil
* the fil
* @param selectedImage
* the selected image
* @param mContext
* the m context
* @return the bitmap
*/
public static Bitmap decodeStrem(File fil, Uri selectedImage,
Context mContext) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(mContext.getContentResolver()
.openInputStream(selectedImage));
final int THUMBNAIL_SIZE = getThumbSize(bitmap);
bitmap = Bitmap.createScaledBitmap(bitmap, THUMBNAIL_SIZE,
THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos
.toByteArray()));
return bitmap = rotateImage(bitmap, fil.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* Rotate image.
*
* @param bmp
* the bmp
* @param imageUrl
* the image url
* @return the bitmap
*/
public static Bitmap rotateImages(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}
/**
* Decode file.
*
* @param f
* the f
* @param sampling
* the sampling
* @param check
* the check
* @return the bitmap
*/
public static Bitmap decodeFile(File f, int sampling) {
try {
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = true;
BitmapFactory.decodeStream(
new FileInputStream(f.getAbsolutePath()), null, o2);
o2.inSampleSize = sampling;
o2.inTempStorage = new byte[48 * 1024];
o2.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(
new FileInputStream(f.getAbsolutePath()), null, o2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap = rotateImage(bitmap, f.getAbsolutePath());
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
return null;
}
/**
* Rotate image.
*
* @param bmp
* the bmp
* @param imageUrl
* the image url
* @return the bitmap
*/
public static Bitmap rotateImage(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}
/**
* Gets the thumb size.
*
* @param bitmap
* the bitmap
* @return the thumb size
*/
public static int getThumbSize(Bitmap bitmap) {
int THUMBNAIL_SIZE = 250;
if (bitmap.getWidth() < 300) {
THUMBNAIL_SIZE = 250;
} else if (bitmap.getWidth() < 600) {
THUMBNAIL_SIZE = 500;
} else if (bitmap.getWidth() < 1000) {
THUMBNAIL_SIZE = 750;
} else if (bitmap.getWidth() < 2000) {
THUMBNAIL_SIZE = 1500;
} else if (bitmap.getWidth() < 4000) {
THUMBNAIL_SIZE = 2000;
} else if (bitmap.getWidth() > 4000) {
THUMBNAIL_SIZE = 2000;
}
return THUMBNAIL_SIZE;
}
}
import java.io.ByteArrayInputStream;
导入java.io.ByteArrayOutputStream;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.util.Calendar;
导入android.app.Activity;
导入android.content.Context;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.Matrix;
导入android.hardware.Camera;
导入android.hardware.Camera.PictureCallback;
导入android.media.ExifInterface;
导入android.net.Uri;
导入android.os.Bundle;
导入android.os.Environment;
导入android.view.view;
导入android.widget.Button;
导入android.widget.FrameLayout;
导入android.widget.ImageView;
导入android.widget.Toast;
公共类CameraActivity扩展了活动{
私人摄像机麦卡梅拉;
私人摄像审查mCameraPreview;
私人按钮捕获按钮;
私有图像视图showImageView;
受保护的字符串imageFilePath;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_视图);
mCamera=getCameraInstance();
mCameraPreview=新的CameraPreview(此,mCamera);
FrameLayout preview=(FrameLayout)findviewbyd(R.id.camera\u preview);
showImageView=(ImageView)findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
captureButton=(按钮)findViewById(R.id.Button\u捕获);
captureButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
takePicture(null,null,jpeg回调);
}
});
}
私人摄像机getCameraInstance(){
摄像头=空;
试一试{
camera=camera.open();
}捕获(例外e){
//无法获取相机或相机不存在
}
返回摄像机;
}
/**jpeg回调*/
PictureCallback jpegCallback=新建PictureCallback(){
公共void onPictureTaken(字节[]数据,摄像头){
FileOutputStream扩展流=null;
试一试{
文件miDirs=新文件(
getExternalStorageDirectory()+“/myphotos”);
如果(!miDirs.exists())
miDirs.mkdirs();
最终日历c=Calendar.getInstance();
字符串new\u Date=c.get(日历.月日)+“-”
+((c.get(日历月))+1)+“-”
+c.get(Calendar.YEAR)+“”+c.get(Calendar.HOUR)
+“-”+c.get(日历分钟)+“-”
+c.get(日历秒);
imageFilePath=String.format(
Environment.getExternalStorageDirectory()+“/myphotos”
+“/%s.jpg”、“te1t(“+new_Date+”);
Uri selectedImage=Uri.parse(imageFilePath);
文件文件=新文件(imageFilePath);
字符串路径=file.getAbsolutePath();
位图=空;
outStream=新文件OutputStream(文件);
外扩。写入(数据);
exptream.close();
if(路径!=null){
if(path.startsWith(“内容”)){
位图=解码字符串(文件,选择图像,
摄像活动(此);
}否则{
位图=解码文件(文件,10);
}
}
if(位图!=null){
showImageView.setImageBitmap(位图);
Toast.makeText(CameraActivity.this,
“成功捕获图片:”,Toast.LENGTH\u LONG)
.show();
}否则{
Toast.makeText(CameraActivity.this,
未能捕获图片。请重试:“,
Toast.LENGTH_LONG).show();
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
}
}
};
/**
*解码strem。
*
*@param-fil
*电影
*@param selectedImage
*选定的图像
*@param mContext
*m语境
*@返回位图
*/
公共静态位图解码器(文件fil,Uri selectedImage,
上下文(mContext){
位图=空;
试一试{
bitmap=BitmapFactory.decodeStream(mContext.getContentResolver()
.openInputStream(selectedImage));
最终整型缩略图大小=位图大小;
位图=位图。createScaledBitmap(位图、缩略图大小、,
缩略图(U大小,错误);
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
压缩(bitmap.CompressFormat.JPEG,100,baos);
位图=位图工厂.decodeStream(新的ByteArrayInputStream(BAS
.toByteArray());
返回位图=旋转图像(位图,fil.getAbsolutePath());
}捕获(例外e){
e、 印刷品