android自定义Camera拍照并查看图片

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

1、打开相机

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <SurfaceView
    android:id="@+id/sv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

  <Button
    android:id="@+id/btn_camera"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="拍照" />

</LinearLayout>

2、获取相机并开启预览

/**
   * 获取系统相机
   * 
   * @return
   */
  private Camera getcCamera() {
    Camera camera = null;
    try {
      camera = Camera.open();
    } catch (Exception e) {
      camera = null;
    }
    return camera;
  }

/**
   * 显示相机预览图片
   * 
   * @return
   */
  private void showCameraView(Camera camera,SurfaceHolder holder)
  {
    try {
      camera.setPreviewDisplay(holder);
      camera.setDisplayOrientation(90);
      camera.startPreview();
    }catch (Exception e){
      e.printStackTrace();
    };

  }
/**
** 实现界面回调处理
*/
  @Override
  public void surfaceCreated(SurfaceHolder holder) {
    showCameraView(mCamera, holder);
  }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    mCamera.stopPreview();
    showCameraView(mCamera, holder);
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder holder) {
    clearCamera();
  }
}

3、相机主页面处理

public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback{

  private SurfaceView sv;
  private Camera mCamera;
  private SurfaceHolder holder;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    sv = (SurfaceView)findViewById(R.id.sv);
    holder = sv.getHolder();
    holder.addCallback(this);

    findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // 获取当前相机参数
        Camera.Parameters parameters = mCamera.getParameters();
        // 设置相片格式
        parameters.setPictureFormat(ImageFormat.JPEG);
        // 设置预览大小
        parameters.setPreviewSize(800, 480);
        // 设置对焦方式,这里设置自动对焦
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        mCamera.autoFocus(new Camera.AutoFocusCallback() {

          @Override
          public void onAutoFocus(boolean success, Camera camera) {
            // 判断是否对焦成功
            if (success) {
              // 拍照 第三个参数为拍照回调
              mCamera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                  // data为完整数据
                  File file = new File("/sdcard/photo.png");
                  // 使用流进行读写
                  try {
                    FileOutputStream fos = new FileOutputStream(file);
                    try {
                      fos.write(data);
                      // 关闭流
                      fos.close();
                      // 查看图片
                      Intent intent = new Intent();
                      // 传递路径
                      intent.putExtra("path", file.getAbsolutePath());
                      setResult(0,intent);
                      finish();
                    } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                  } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  }
                }
              });
            }
          }
        });
      }
    });

  }

 @Override
  protected void onResume() {
    super.onResume();
    if (mCamera == null) {
      mCamera = getCamera();
      if (holder != null) {
        showCameraView(mCamera, holder);
      }
    }
  }
  @Override
  protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    // activity暂停时我们释放相机内存
    clearCamera();

  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  /**
   * 释放相机的内存
   */
  private void clearCamera() {

    // 释放hold资源
    if (mCamera != null) {
      // 停止预览
      mCamera.stopPreview();
      mCamera.setPreviewCallback(null);
      // 释放相机资源
      mCamera.release();
      mCamera = null;
    }
  }

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

public class MainActivity extends AppCompatActivity {

  private ImageView cameraIv;

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == 0 && requestCode == 100)
    {
      String path = data.getStringExtra("path");
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(path, options);
      ImageSize imageSize = getImageViewSize(cameraIv);
      options.inSampleSize = caculateInSampleSize(options,
          imageSize.width, imageSize.height);

      // 使用获得到的InSampleSize再次解析图片
      options.inJustDecodeBounds = false;
      Bitmap bitmap = BitmapFactory.decodeFile(path, options);
      cameraIv.setImageBitmap(bitmap);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button openButton = (Button) findViewById(R.id.button);
    cameraIv = (ImageView) findViewById(R.id.imageView);



    openButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this,CameraActivity.class);
        startActivityForResult(intent,100);
      }
    });
  }

   /* 根据需求的宽和高以及图片实际的宽和高计算SampleSize
   *
       * @param options
   * @param width
   * @param height
   * @return
       */
  public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,
                      int reqHeight)
  {
    int width = options.outWidth;
    int height = options.outHeight;

    int inSampleSize = 1;

    if (width > reqWidth || height > reqHeight)
    {
      int widthRadio = Math.round(width * 1.0f / reqWidth);
      int heightRadio = Math.round(height * 1.0f / reqHeight);

      inSampleSize = Math.max(widthRadio, heightRadio);
    }

    return inSampleSize;
  }

  public static ImageSize getImageViewSize(ImageView imageView)
  {

    ImageSize imageSize = new ImageSize();
    DisplayMetrics displayMetrics = imageView.getContext().getResources()
        .getDisplayMetrics();

    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)imageView.getLayoutParams();

    int width = imageView.getWidth();// 获取imageview的实际宽度
    if (width <= 0)
    {
      width = lp.width;// 获取imageview在layout中声明的宽度
    }

    if (width <= 0)
    {
      width = displayMetrics.widthPixels;
    }

    int height = imageView.getHeight();// 获取imageview的实际高度
    if (height <= 0)
    {
      height = lp.height;// 获取imageview在layout中声明的宽度
    }

    if (height <= 0)
    {
      height = displayMetrics.heightPixels;
    }
    imageSize.width = width;
    imageSize.height = height;

    return imageSize;
  }

  public static class ImageSize
  {
    int width;
    int height;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。