当前位置:   article > 正文

Android 调用系统中的相机应用_android provider 非activity跳转系统相机

android provider 非activity跳转系统相机

通过Intent直接调用系统相机

  直接调用系统的相机应用,只需要在Intent对象中传入相应的参数即可,总体来说需要以下三步

  1. Compose a Camera Intent

  MediaStore.ACTION_IMAGE_CAPTURE 拍照;

  MediaStore.ACTION_VIDEO_CAPTURE录像。


  2. Start the Camera Intent

  使用startActivityForResult()方法,并传入上面的intent对象。

  之后,系统自带的相机应用就会启动,用户就可以用它来拍照或者录像。

 

  3. Receive the Intent Result

   用onActivityResult()接收传回的图像,当用户拍完照片或者录像,或者取消后,系统都会调用这个函数。

 

关于接收图像

  如果不设置接收图像的部分,拍照完毕后将会返回到原来的activity,相片会自动存储在拍照应用的默认存储位置。

 

  为了接收图像,需要做以下几个工作:

  1.指定图像的存储位置,一般图像都是存储在外部存储设备,即SD卡上。

  你可以考虑的标准的位置有以下两个:

  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

  这个方法返回图像和视频的标准共享位置,别的应用也可以访问,如果你的应用被卸载了,这个路径下的文件是会保留的

  为了区分,你可以在这个路径下为你的应用创建一个子文件夹。

  Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)

  这个方法返回的路径是和你的应用相关的一个存储图像和视频的方法。

  如果应用被卸载,这个路径下的东西全都会被删除。

  这个路径没有什么安全性限制,别的应用也可以自由访问里面的文件。

 

  2.为了接收intent的结果,需要覆写activity中的 onActivityResult() 方法。

  前面说过,可以不设置相机返回的图像结果的操作,此时在startActivityForResult()中不需要给intent传入额外的数据,这样在onActivityResult()回调时,返回的Intent data不为null,照片存在系统默认的图片存储路径下。

  但是如果想得到这个图像,你必须制定要存储的目标File,并且把它作为URI传给启动的intent,使用MediaStore.EXTRA_OUTPUT作为关键字。

  这样的话,拍摄出来的照片将会存在这个特殊指定的地方,此时没有thumbnail会被返回给activity的回调函数,所以接收到的Intent data为null

 

程序实例

  附上程序代码,其中视频存储的返回结果部分没有写代码,视频拍摄后会存入系统应用的默认位置。

在原来的基础上添加静默拍照。


  1. //系统自带相机应用测试
  2. package com.kelly.systemcameraandvedio;
  3. import java.io.File;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. import android.app.Activity;
  7. import android.content.Intent;
  8. import android.graphics.Bitmap;
  9. import android.graphics.BitmapFactory;
  10. import android.hardware.Camera;
  11. import android.net.Uri;
  12. import android.os.Bundle;
  13. import android.os.Environment;
  14. import android.provider.MediaStore;
  15. import android.util.Log;
  16. import android.view.SurfaceHolder;
  17. import android.view.SurfaceView;
  18. import android.view.View;
  19. import android.view.View.OnClickListener;
  20. import android.widget.Button;
  21. import android.widget.ImageView;
  22. import android.widget.RelativeLayout;
  23. import android.widget.Toast;
  24. public class MainActivity extends Activity {
  25. private static final String LOG_TAG = "HelloCamera";
  26. private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
  27. private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
  28. public static final int MEDIA_TYPE_IMAGE = 1;
  29. public static final int MEDIA_TYPE_VIDEO = 2;
  30. private Button takePicBtn = null;
  31. private Button takeVideoBtn = null;
  32. private Button takePicSoundless = null;
  33. private ImageView imageView = null;
  34. private Uri fileUri;
  35. @Override
  36. public void onCreate(Bundle savedInstanceState) {
  37. Log.i(LOG_TAG, "onCreate");
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.activity_main);
  40. takePicBtn = (Button) findViewById(R.id.but_takePic);
  41. takePicBtn.setOnClickListener(takePiClickListener);
  42. takeVideoBtn = (Button) findViewById(R.id.but_takeVedio);
  43. takeVideoBtn.setOnClickListener(takeVideoClickListener);
  44. takePicSoundless = (Button) findViewById(R.id.but_takePicBackground);
  45. takePicSoundless
  46. .setOnClickListener(new takePicSoundlessClickListener());
  47. imageView = (ImageView) findViewById(R.id.imageview_leo);
  48. }
  49. /**
  50. * 静默拍照
  51. *
  52. * @author Administrator
  53. *
  54. */
  55. private class takePicSoundlessClickListener implements OnClickListener {
  56. public void onClick(View v) {
  57. Intent intent = new Intent(MainActivity.this, CameraActivity.class);
  58. startActivity(intent);
  59. }
  60. }
  61. private final OnClickListener takePiClickListener = new View.OnClickListener() {
  62. @Override
  63. public void onClick(View v) {
  64. Log.i(LOG_TAG, "Take Picture Button Click");
  65. // 利用系统自带的相机应用:拍照
  66. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  67. // create a file to save the image
  68. fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
  69. // 此处这句intent的值设置关系到后面的onActivityResult中会进入那个分支,即关系到data是否为null,如果此处指定,则后来的data为null
  70. // set the image file name
  71. intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
  72. // // set the video image quality to high
  73. // intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
  74. startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
  75. }
  76. };
  77. private final OnClickListener takeVideoClickListener = new View.OnClickListener() {
  78. @Override
  79. public void onClick(View v) {
  80. Log.i(LOG_TAG, "Take Video Button Click");
  81. // 摄像
  82. Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
  83. // create a file to save the video
  84. fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
  85. // set the image file name
  86. intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
  87. // set the video image quality to high
  88. intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
  89. startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
  90. }
  91. };
  92. /** Create a file Uri for saving an image or video */
  93. private static Uri getOutputMediaFileUri(int type) {
  94. return Uri.fromFile(getOutputMediaFile(type));
  95. }
  96. /** Create a File for saving an image or video */
  97. private static File getOutputMediaFile(int type) {
  98. // To be safe, you should check that the SDCard is mounted
  99. // using Environment.getExternalStorageState() before doing this.
  100. File mediaStorageDir = null;
  101. try {
  102. // This location works best if you want the created images to be
  103. // shared
  104. // between applications and persist after your app has been
  105. // uninstalled.
  106. mediaStorageDir = new File(
  107. Environment
  108. .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
  109. "MyCameraApp");
  110. Log.i(LOG_TAG, "Successfully created mediaStorageDir: "
  111. + mediaStorageDir);
  112. } catch (Exception e) {
  113. e.printStackTrace();
  114. Log.i(LOG_TAG, "Error in Creating mediaStorageDir: "
  115. + mediaStorageDir);
  116. }
  117. // Create the storage directory if it does not exist
  118. if (!mediaStorageDir.exists()) {
  119. if (!mediaStorageDir.mkdirs()) {
  120. // 在SD卡上创建文件夹需要权限:
  121. // <uses-permission
  122. // android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  123. Log.i(LOG_TAG,
  124. "failed to create directory, check if you have the WRITE_EXTERNAL_STORAGE permission");
  125. return null;
  126. }
  127. }
  128. // Create a media file name
  129. String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
  130. .format(new Date());
  131. File mediaFile;
  132. if (type == MEDIA_TYPE_IMAGE) {
  133. mediaFile = new File(mediaStorageDir.getPath() + File.separator
  134. + "IMG_" + timeStamp + ".jpg");
  135. } else if (type == MEDIA_TYPE_VIDEO) {
  136. mediaFile = new File(mediaStorageDir.getPath() + File.separator
  137. + "VID_" + timeStamp + ".mp4");
  138. } else {
  139. return null;
  140. }
  141. return mediaFile;
  142. }
  143. @Override
  144. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  145. super.onActivityResult(requestCode, resultCode, data);
  146. Log.i(LOG_TAG, "onActivityResult: requestCode: " + requestCode
  147. + ", resultCode: " + requestCode + ", data: " + data);
  148. // 如果是拍照
  149. if (CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE == requestCode) {
  150. Log.i(LOG_TAG, "CAPTURE_IMAGE");
  151. if (RESULT_OK == resultCode) {
  152. Log.i(LOG_TAG, "RESULT_OK");
  153. // Check if the result includes a thumbnail Bitmap
  154. if (data != null) {
  155. // 没有指定特定存储路径的时候
  156. Log.i(LOG_TAG,
  157. "data is NOT null, file on default position.");
  158. // 指定了存储路径的时候(intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);)
  159. // Image captured and saved to fileUri specified in the
  160. // Intent
  161. Toast.makeText(this, "Image saved to:\n" + data.getData(),
  162. Toast.LENGTH_LONG).show();
  163. if (data.hasExtra("data")) {
  164. Bitmap thumbnail = data.getParcelableExtra("data");
  165. imageView.setImageBitmap(thumbnail);
  166. }
  167. } else {
  168. Log.i(LOG_TAG,
  169. "data IS null, file saved on target position.");
  170. // If there is no thumbnail image data, the image
  171. // will have been stored in the target output URI.
  172. // Resize the full image to fit in out image view.
  173. int width = imageView.getWidth();
  174. int height = imageView.getHeight();
  175. BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
  176. factoryOptions.inJustDecodeBounds = true;
  177. BitmapFactory.decodeFile(fileUri.getPath(), factoryOptions);
  178. int imageWidth = factoryOptions.outWidth;
  179. int imageHeight = factoryOptions.outHeight;
  180. // Determine how much to scale down the image
  181. int scaleFactor = Math.min(imageWidth / width, imageHeight
  182. / height);
  183. // Decode the image file into a Bitmap sized to fill the
  184. // View
  185. factoryOptions.inJustDecodeBounds = false;
  186. factoryOptions.inSampleSize = scaleFactor;
  187. factoryOptions.inPurgeable = true;
  188. Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
  189. factoryOptions);
  190. imageView.setImageBitmap(bitmap);
  191. }
  192. } else if (resultCode == RESULT_CANCELED) {
  193. // User cancelled the image capture
  194. } else {
  195. // Image capture failed, advise user
  196. }
  197. }
  198. // 如果是录像
  199. if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
  200. Log.i(LOG_TAG, "CAPTURE_VIDEO");
  201. if (resultCode == RESULT_OK) {
  202. } else if (resultCode == RESULT_CANCELED) {
  203. // User cancelled the video capture
  204. } else {
  205. // Video capture failed, advise user
  206. }
  207. }
  208. }
  209. }

静默拍照 CameraActivity

  1. package com.kelly.systemcameraandvedio;
  2. /**
  3. * 用来拍照的Activity
  4. *
  5. */
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. import android.annotation.SuppressLint;
  12. import android.annotation.TargetApi;
  13. import android.app.Activity;
  14. import android.content.Context;
  15. import android.content.pm.PackageManager;
  16. import android.graphics.Bitmap;
  17. import android.graphics.BitmapFactory;
  18. import android.graphics.Matrix;
  19. import android.hardware.Camera;
  20. import android.hardware.Camera.AutoFocusCallback;
  21. import android.hardware.Camera.PictureCallback;
  22. import android.os.Build;
  23. import android.os.Bundle;
  24. import android.os.Environment;
  25. import android.util.Log;
  26. import android.view.SurfaceHolder;
  27. import android.view.SurfaceView;
  28. import android.view.Window;
  29. import android.view.WindowManager;
  30. import android.widget.Toast;
  31. @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  32. @SuppressLint("NewApi")
  33. public class CameraActivity extends Activity {
  34. private SurfaceView mySurfaceView;
  35. private SurfaceHolder myHolder;
  36. private Camera myCamera;
  37. private static final String TAG = "CameraActivity";
  38. @Override
  39. protected void onCreate(Bundle savedInstanceState) {
  40. super.onCreate(savedInstanceState);
  41. // 无title
  42. requestWindowFeature(Window.FEATURE_NO_TITLE);
  43. // 全屏
  44. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  45. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  46. // 设置布局
  47. setContentView(R.layout.activity_camera);
  48. Log.i(TAG, "oncreate");
  49. // 初始化surface
  50. initSurface();
  51. // 这里得开线程进行拍照,因为Activity还未完全显示的时候,是无法进行拍照的,SurfaceView必须先显示
  52. new Thread(new Runnable() {
  53. @Override
  54. public void run() {
  55. // 初始化camera并对焦拍照
  56. initCamera();
  57. }
  58. }).start();
  59. }
  60. // 初始化surface
  61. @SuppressWarnings("deprecation")
  62. private void initSurface() {
  63. // 初始化surfaceview
  64. mySurfaceView = (SurfaceView) findViewById(R.id.camera_surfaceview);
  65. // 初始化surfaceholder
  66. myHolder = mySurfaceView.getHolder();
  67. }
  68. // 初始化摄像头
  69. private void initCamera() {
  70. // 如果存在摄像头
  71. if (checkCameraHardware(getApplicationContext())) {
  72. // 获取摄像头(首选前置,无前置选后置)
  73. if (openFacingFrontCamera()) {
  74. Log.i(TAG, "openCameraSuccess");
  75. // 进行对焦
  76. autoFocus();
  77. } else {
  78. Log.i(TAG, "openCameraFailed");
  79. }
  80. }
  81. }
  82. // 对焦并拍照
  83. private void autoFocus() {
  84. try {
  85. // 因为开启摄像头需要时间,这里让线程睡两秒
  86. Thread.sleep(2000);
  87. } catch (InterruptedException e) {
  88. e.printStackTrace();
  89. }
  90. // 自动对焦
  91. myCamera.autoFocus(myAutoFocus);
  92. // 对焦后拍照
  93. myCamera.takePicture(null, null, myPicCallback);
  94. }
  95. // 判断是否存在摄像头
  96. private boolean checkCameraHardware(Context context) {
  97. if (context.getPackageManager().hasSystemFeature(
  98. PackageManager.FEATURE_CAMERA)) {
  99. // 设备存在摄像头
  100. return true;
  101. } else {
  102. // 设备不存在摄像头
  103. return false;
  104. }
  105. }
  106. // 得到后置摄像头
  107. private boolean openFacingFrontCamera() {
  108. // 尝试开启前置摄像头
  109. Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
  110. for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) {
  111. Camera.getCameraInfo(camIdx, cameraInfo);
  112. if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
  113. try {
  114. Log.i(TAG, "tryToOpenCamera");
  115. myCamera = Camera.open(camIdx);
  116. } catch (RuntimeException e) {
  117. e.printStackTrace();
  118. return false;
  119. }
  120. }
  121. }
  122. // 如果开启前置失败(无前置)则开启后置
  123. if (myCamera == null) {
  124. for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) {
  125. Camera.getCameraInfo(camIdx, cameraInfo);
  126. if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
  127. try {
  128. myCamera = Camera.open(camIdx);
  129. } catch (RuntimeException e) {
  130. return false;
  131. }
  132. }
  133. }
  134. }
  135. try {
  136. // 这里的myCamera为已经初始化的Camera对象
  137. myCamera.setPreviewDisplay(myHolder);
  138. } catch (IOException e) {
  139. e.printStackTrace();
  140. myCamera.stopPreview();
  141. myCamera.release();
  142. myCamera = null;
  143. }
  144. myCamera.startPreview();
  145. return true;
  146. }
  147. // 自动对焦回调函数(空实现)
  148. private AutoFocusCallback myAutoFocus = new AutoFocusCallback() {
  149. @Override
  150. public void onAutoFocus(boolean success, Camera camera) {
  151. }
  152. };
  153. // 拍照成功回调函数
  154. private PictureCallback myPicCallback = new PictureCallback() {
  155. @Override
  156. public void onPictureTaken(byte[] data, Camera camera) {
  157. // 完成拍照后关闭Activity
  158. CameraActivity.this.finish();
  159. // 将得到的照片进行270°旋转,使其竖直
  160. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
  161. Matrix matrix = new Matrix();
  162. matrix.preRotate(270);
  163. bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
  164. bitmap.getHeight(), matrix, true);
  165. String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
  166. .format(new Date());
  167. // 创建并保存图片文件
  168. File pictureFile = new File(getDir(), "IMG_" + timeStamp + ".jpg");
  169. try {
  170. FileOutputStream fos = new FileOutputStream(pictureFile);
  171. bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
  172. fos.close();
  173. } catch (Exception error) {
  174. Toast.makeText(CameraActivity.this, "拍照失败", Toast.LENGTH_SHORT)
  175. .show();
  176. ;
  177. Log.i(TAG, "保存照片失败" + error.toString());
  178. error.printStackTrace();
  179. myCamera.stopPreview();
  180. myCamera.release();
  181. myCamera = null;
  182. }
  183. Log.i(TAG, "获取照片成功");
  184. Toast.makeText(CameraActivity.this, "获取照片成功", Toast.LENGTH_SHORT)
  185. .show();
  186. ;
  187. myCamera.stopPreview();
  188. myCamera.release();
  189. myCamera = null;
  190. }
  191. };
  192. // 获取文件夹
  193. private File getDir() {
  194. // 得到SD卡根目录
  195. File dir = Environment.getExternalStorageDirectory();
  196. if (dir.exists()) {
  197. return dir;
  198. } else {
  199. dir.mkdirs();
  200. return dir;
  201. }
  202. }
  203. }


参考:1.http://www.cnblogs.com/mengdd/archive/2013/03/31/2991932.html

  2.http://download.csdn.net/detail/a740169405/6344845

代码下载:http://download.csdn.net/detail/leokelly001/8173715



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/175304
推荐阅读
相关标签
  

闽ICP备14008679号