Android -- Camera 照相和录像, 使用系统APP和自己生成Camera
来源:互联网 发布:资生堂红腰子精华 知乎 编辑:程序博客网 时间:2024/05/12 13:44
1. 使用系统Camera APP 照相和录像
示例代码:
需要添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.CAMERA" />
activity_main.xml 布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="click" android:text="拍照" /> <ImageView android:id="@+id/iv" android:layout_width="100dip" android:layout_height="100dip" /></RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {private ImageView iv;private Uri fileUri;public static final int MEDIA_TYPE_IMAGE = 1;public static final int MEDIA_TYPE_VIDEO = 2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);iv = (ImageView) findViewById(R.id.iv);}/** Create a file Uri for saving an image or video */private static Uri getOutputMediaFileUri(int type) {return Uri.fromFile(getOutputMediaFile(type));}/** Create a File for saving an image or video */private static File getOutputMediaFile(int type) {//SDcard/Pictures/MyCameraApp 目录File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");// 创建sd卡的目录if (!mediaStorageDir.exists()) {if (!mediaStorageDir.mkdirs()) {Log.d("MyCameraApp", "failed to create directory");return null;}}// Create a media file nameString timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());File mediaFile;if (type == MEDIA_TYPE_IMAGE) {mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg");} else if (type == MEDIA_TYPE_VIDEO) {mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "VID_" + timeStamp + ".mp4");} else {return null;}return mediaFile;}public void click(View view) {// create Intent to take a picture and return control to the calling// application MediaStore.ACTION_VIDEO_CAPTUREIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file// to save the// imageintent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file// name// start the image capture IntentstartActivityForResult(intent, 0);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {try {InputStream is = getContentResolver().openInputStream(fileUri);Bitmap bitmap = BitmapFactory.decodeStream(is);iv.setImageBitmap(bitmap);} catch (FileNotFoundException e) {e.printStackTrace();}super.onActivityResult(requestCode, resultCode, data);}}
2. 使用系统API 自己创建Camera
示例代码:
需要权限
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-feature android:name="android.hardware.camera" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <FrameLayout android:id="@+id/camera_preview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <Button android:id="@+id/button_capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Capture" /></LinearLayout>
CameraPreview.java 拍照之前的预览显示
import java.io.IOException;import android.content.Context;import android.hardware.Camera;import android.util.Log;import android.view.SurfaceHolder;import android.view.SurfaceView;public class CameraPreview extends SurfaceView implementsSurfaceHolder.Callback {private static final String TAG = "CameraPreview";private SurfaceHolder mHolder;private Camera mCamera;public CameraPreview(Context context, Camera camera) {super(context);mCamera = camera;// Install a SurfaceHolder.Callback so we get notified when the// underlying surface is created and destroyed.mHolder = getHolder();mHolder.addCallback(this);// deprecated setting, but required on Android versions prior to 3.0mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);}public void surfaceCreated(SurfaceHolder holder) {// The Surface has been created, now tell the camera where to draw the// preview.try {mCamera.setPreviewDisplay(holder);mCamera.startPreview();} catch (IOException e) {Log.d(TAG, "Error setting camera preview: " + e.getMessage());}}public void surfaceDestroyed(SurfaceHolder holder) {// empty. Take care of releasing the Camera preview in your activity.}public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {// If your preview can change or rotate, take care of those events here.// Make sure to stop the preview before resizing or reformatting it.if (mHolder.getSurface() == null) {// preview surface does not existreturn;}// stop preview before making changestry {mCamera.stopPreview();} catch (Exception e) {// ignore: tried to stop a non-existent preview}// set preview size and make any resize, rotate or// reformatting changes here// start preview with new settingstry {mCamera.setPreviewDisplay(mHolder);mCamera.startPreview();} catch (Exception e) {Log.d(TAG, "Error starting camera preview: " + e.getMessage());}}}
MainActivity.java
import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import android.os.Bundle;import android.os.Environment;import android.app.Activity;import android.content.Context;import android.content.pm.PackageManager;import android.hardware.Camera;import android.hardware.Camera.PictureCallback;import android.util.Log;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.FrameLayout;public class MainActivity extends Activity {Camera mCamera;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);if (checkCameraHardware(this)) {// Create an instance of CameramCamera = getCameraInstance();// 解决成像旋转90°问题mCamera.setDisplayOrientation(90);// Create our Preview view and set it as the content of our// activity.CameraPreview mPreview = new CameraPreview(this, mCamera);FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);preview.addView(mPreview);}// Add a listener to the Capture buttonButton captureButton = (Button) findViewById(R.id.button_capture);captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { mCamera.autoFocus(null); // get an image from the camera mCamera.takePicture(null, null, new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = new File(Environment.getExternalStorageDirectory(),"my.jpg"); String TAG="PictureCallback"; try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } }); } });}/** 检查是否有照相机 */private boolean checkCameraHardware(Context context) {if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {// this device has a camerareturn true;} else {// no camera on this devicereturn false;}}/** 获取一个照相机. */public static Camera getCameraInstance() {Camera c = null;try {c = Camera.open(); // attempt to get a Camera instance//Camera.open(1);//打开前置摄像头} catch (Exception e) {// Camera is not available (in use or does not exist)}return c; // returns null if camera is unavailable}}
0 0
- Android -- Camera 照相和录像, 使用系统APP和自己生成Camera
- Android Camera 照相和录像
- Android 照相和录像
- Android 中使用Camera照相
- Android实战技巧之三十一:拍照和录像 with Camera
- android下自定义Camera进行录像和拍照
- Android系统Camera录像过程分析
- Android系统Camera录像过程分析
- Android系统Camera录像过程分析
- Android系统Camera录像过程分析
- Android系统Camera录像过程分析
- Android系统Camera录像过程分析
- Android 的camera.setPreviewCallbackWithBuffer和camera.addCallbackBuffer
- Android 的camera.setPreviewCallbackWithBuffer和camera.addCallbackBuffer
- android使用camera和matrix,canvas小结
- android使用mediarecorder和camera录制视频
- Android Camera使用和人脸检测
- 整合Camera和MediaRecorder实现拍照和录像
- 权限矩阵的创造(一)
- Wireshark抓包工具--TCP数据包seq ack等解读
- 学习数据分析、挖掘的22本好书
- Oracle case when 查询和更新(不积跬步,无以至千里)
- 帽子问题
- Android -- Camera 照相和录像, 使用系统APP和自己生成Camera
- Makefile语法简介
- linux下安装vsftp(自己验证)
- 断开某tcp连接
- Java中调用dll动态库的简洁方法
- 【SAP】笔试题
- hdu 1024 Max Sum Plus Plus
- 有关ICP(Internet Cache Protocol)协议的总结(三)
- javascript中的闭包使用例子与解释