查看: 464|回复: 0

[Android教程] android自定义Camera拍照并查看图片

发表于 2017-11-28 08:00:01

本文实例为大家分享了android自定义Camera拍照并查看图片的具体代码,供大家参考,具体内容如下

1、打开相机

a.预览拍摄图片,需用到SurfaceView,并且实现其回调函数implements SurfaceHolder.Callback;
activity_camera.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <SurfaceView
  7. android:id="@+id/sv"
  8. android:layout_width="match_parent"
  9. android:layout_height="0dp"
  10. android:layout_weight="1" />
  11. <Button
  12. android:id="@+id/btn_camera"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:text="拍照" />
  16. </LinearLayout>
复制代码

2、获取相机并开启预览

  1. /**
  2. * 获取系统相机
  3. *
  4. * @return
  5. */
  6. private Camera getcCamera() {
  7. Camera camera = null;
  8. try {
  9. camera = Camera.open();
  10. } catch (Exception e) {
  11. camera = null;
  12. }
  13. return camera;
  14. }
复制代码
  1. /**
  2. * 显示相机预览图片
  3. *
  4. * @return
  5. */
  6. private void showCameraView(Camera camera,SurfaceHolder holder)
  7. {
  8. try {
  9. camera.setPreviewDisplay(holder);
  10. camera.setDisplayOrientation(90);
  11. camera.startPreview();
  12. }catch (Exception e){
  13. e.printStackTrace();
  14. };
  15. }
复制代码
  1. /**
  2. ** 实现界面回调处理
  3. */
  4. @Override
  5. public void surfaceCreated(SurfaceHolder holder) {
  6. showCameraView(mCamera, holder);
  7. }
  8. @Override
  9. public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  10. mCamera.stopPreview();
  11. showCameraView(mCamera, holder);
  12. }
  13. @Override
  14. public void surfaceDestroyed(SurfaceHolder holder) {
  15. clearCamera();
  16. }
  17. }
复制代码

3、相机主页面处理

  1. public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback{
  2. private SurfaceView sv;
  3. private Camera mCamera;
  4. private SurfaceHolder holder;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_camera);
  9. sv = (SurfaceView)findViewById(R.id.sv);
  10. holder = sv.getHolder();
  11. holder.addCallback(this);
  12. findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
  13. @Override
  14. public void onClick(View v) {
  15. // 获取当前相机参数
  16. Camera.Parameters parameters = mCamera.getParameters();
  17. // 设置相片格式
  18. parameters.setPictureFormat(ImageFormat.JPEG);
  19. // 设置预览大小
  20. parameters.setPreviewSize(800, 480);
  21. // 设置对焦方式,这里设置自动对焦
  22. parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
  23. mCamera.autoFocus(new Camera.AutoFocusCallback() {
  24. @Override
  25. public void onAutoFocus(boolean success, Camera camera) {
  26. // 判断是否对焦成功
  27. if (success) {
  28. // 拍照 第三个参数为拍照回调
  29. mCamera.takePicture(null, null, new Camera.PictureCallback() {
  30. @Override
  31. public void onPictureTaken(byte[] data, Camera camera) {
  32. // data为完整数据
  33. File file = new File("/sdcard/photo.png");
  34. // 使用流进行读写
  35. try {
  36. FileOutputStream fos = new FileOutputStream(file);
  37. try {
  38. fos.write(data);
  39. // 关闭流
  40. fos.close();
  41. // 查看图片
  42. Intent intent = new Intent();
  43. // 传递路径
  44. intent.putExtra("path", file.getAbsolutePath());
  45. setResult(0,intent);
  46. finish();
  47. } catch (IOException e) {
  48. // TODO Auto-generated catch block
  49. e.printStackTrace();
  50. }
  51. } catch (FileNotFoundException e) {
  52. // TODO Auto-generated catch block
  53. e.printStackTrace();
  54. }
  55. }
  56. });
  57. }
  58. }
  59. });
  60. }
  61. });
  62. }
复制代码
  1. @Override
  2. protected void onResume() {
  3. super.onResume();
  4. if (mCamera == null) {
  5. mCamera = getCamera();
  6. if (holder != null) {
  7. showCameraView(mCamera, holder);
  8. }
  9. }
  10. }
  11. @Override
  12. protected void onPause() {
  13. // TODO Auto-generated method stub
  14. super.onPause();
  15. // activity暂停时我们释放相机内存
  16. clearCamera();
  17. }
  18. @Override
  19. protected void onDestroy() {
  20. super.onDestroy();
  21. }
  22. /**
  23. * 释放相机的内存
  24. */
  25. private void clearCamera() {
  26. // 释放hold资源
  27. if (mCamera != null) {
  28. // 停止预览
  29. mCamera.stopPreview();
  30. mCamera.setPreviewCallback(null);
  31. // 释放相机资源
  32. mCamera.release();
  33. mCamera = null;
  34. }
  35. }
复制代码

4、启动activity(设置拍照完图片路径返回显示图片处理,一定要对图片进行采样率操作(很可能拍照的图片太多而无法显示,又不报任何异常))

  1. public class MainActivity extends AppCompatActivity {
  2. private ImageView cameraIv;
  3. @Override
  4. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  5. if(resultCode == 0 && requestCode == 100)
  6. {
  7. String path = data.getStringExtra("path");
  8. BitmapFactory.Options options = new BitmapFactory.Options();
  9. options.inJustDecodeBounds = true;
  10. BitmapFactory.decodeFile(path, options);
  11. ImageSize imageSize = getImageViewSize(cameraIv);
  12. options.inSampleSize = caculateInSampleSize(options,
  13. imageSize.width, imageSize.height);
  14. // 使用获得到的InSampleSize再次解析图片
  15. options.inJustDecodeBounds = false;
  16. Bitmap bitmap = BitmapFactory.decodeFile(path, options);
  17. cameraIv.setImageBitmap(bitmap);
  18. }
  19. super.onActivityResult(requestCode, resultCode, data);
  20. }
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25. Button openButton = (Button) findViewById(R.id.button);
  26. cameraIv = (ImageView) findViewById(R.id.imageView);
  27. openButton.setOnClickListener(new View.OnClickListener() {
  28. @Override
  29. public void onClick(View v) {
  30. Intent intent = new Intent(MainActivity.this,CameraActivity.class);
  31. startActivityForResult(intent,100);
  32. }
  33. });
  34. }
  35. /* 根据需求的宽和高以及图片实际的宽和高计算SampleSize
  36. *
  37. * @param options
  38. * @param width
  39. * @param height
  40. * @return
  41. */
  42. public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,
  43. int reqHeight)
  44. {
  45. int width = options.outWidth;
  46. int height = options.outHeight;
  47. int inSampleSize = 1;
  48. if (width > reqWidth || height > reqHeight)
  49. {
  50. int widthRadio = Math.round(width * 1.0f / reqWidth);
  51. int heightRadio = Math.round(height * 1.0f / reqHeight);
  52. inSampleSize = Math.max(widthRadio, heightRadio);
  53. }
  54. return inSampleSize;
  55. }
  56. public static ImageSize getImageViewSize(ImageView imageView)
  57. {
  58. ImageSize imageSize = new ImageSize();
  59. DisplayMetrics displayMetrics = imageView.getContext().getResources()
  60. .getDisplayMetrics();
  61. LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)imageView.getLayoutParams();
  62. int width = imageView.getWidth();// 获取imageview的实际宽度
  63. if (width <= 0)
  64. {
  65. width = lp.width;// 获取imageview在layout中声明的宽度
  66. }
  67. if (width <= 0)
  68. {
  69. width = displayMetrics.widthPixels;
  70. }
  71. int height = imageView.getHeight();// 获取imageview的实际高度
  72. if (height <= 0)
  73. {
  74. height = lp.height;// 获取imageview在layout中声明的宽度
  75. }
  76. if (height <= 0)
  77. {
  78. height = displayMetrics.heightPixels;
  79. }
  80. imageSize.width = width;
  81. imageSize.height = height;
  82. return imageSize;
  83. }
  84. public static class ImageSize
  85. {
  86. int width;
  87. int height;
  88. }
  89. }
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条