Android -- Camera 照相和录像, 使用系统APP和自己生成Camera
2014-04-10 10:23
615 查看
1. 使用系统Camera APP 照相和录像
示例代码:
需要添加权限
activity_main.xml 布局
MainActivity.java
2. 使用系统API 自己创建Camera
示例代码:
需要权限
activity_main.xml
CameraPreview.java 拍照之前的预览显示
MainActivity.java
示例代码:
需要添加权限
<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; @Override protected 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 name String 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_CAPTURE Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file // to save the // image intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file // name // start the image capture Intent startActivityForResult(intent, 0); } @Override protected 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 implements SurfaceHolder.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.0 mHolder.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 exist return; } // stop preview before making changes try { 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 settings try { 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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (checkCameraHardware(this)) { // Create an instance of Camera mCamera = 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 button Button 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 camera return true; } else { // no camera on this device return 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 } }
相关文章推荐
- Android 4.3 系统裁剪——删除不使用的app及增加自己app
- android修改系统字体大小,使用隐藏类和方法以及怎么生成系统app使用系统权限
- Android 4.3 系统裁剪——删除不使用的app及添加自己app
- Android 4.3 系统裁剪——删除不使用的app及增加自己app
- Android Camera 使用小结。两种方法:一是调用系统camera app,二是自己写camera程序。
- Android 4.3 系统剪裁——删除不使用的app及增加自己app
- android 分享或者调用系统或者其他app时 应注意! startActivityForResult() 使用
- Android: Receiving Data from the Send Intent,自己app注册系统分享
- Android系统Camera录像过程分析
- 在Android源码环境下编译系统App使用第三方jar包的方法(备忘)
- Android开发之生成自己的签名文件及App签名打包
- 命令行下使用javah命令生成.h文件,出现“错误: 无法访问android.app.Activity 找不到android.app.Activity的类文件”的解决方法
- Android问题集锦之三十九:使用Camera录像的常见问题
- 使用 android 系统提供的 app 打开对应文件
- Android使用自己生成的.so动态函数库
- android技巧:把自己的app变成手机系统自带的app[/system/app]
- Android 中使用Camera照相
- Android开发之生成自己的签名文件及App签名打包
- 命令行下使用javah命令生成.h文件,出现“错误: 无法访问android.app.Activity 找不到android.app.Activity的类文件”的解决方法
- android-- 让你的app无法使用系统截图的探究(接入银联过程中)