• 调用Camera返回为空的分析及处理方法


    前言

    大家可能遇到了这种情况。调用Camera,然后指定自己定义的保存路径,结果返回的Intent为空。我们来分析一下原因。


    分析

    首先看Camera的部分逻辑,在源代码中的Camera.javadoAttach()方法里面。

    // First handle the no crop case -- just return the value.  If the
    // caller specifies a "save uri" then write the data to it's
    // stream. Otherwise, pass back a scaled down version of the bitmap
    // directly in the extras.
    if (mSaveUri != null) {
      OutputStream outputStream = null;
      try {
         outputStream = mContentResolver.openOutputStream(mSaveUri);
         outputStream.write(data);
         outputStream.close();
     
         setResult(RESULT_OK);
         finish();
         } catch (IOException ex) {
             // ignore exception
         } finally {
             Util.closeSilently(outputStream);
         }
    } else {
      Bitmap bitmap = createCaptureBitmap(data);
      setResult(RESULT_OK,
             new Intent("inline-data").putExtra("data", bitmap));
      finish();
    }

    凝视也有明白解释,假如mSaveUri不为空,则直接返回RESULT_OK,不会回传其它不论什么东西。假如为空,则会回传一个bitmap

    再看看我们调用Camera的代码。

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Date date = new Date();
    String photoDCIM = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM; // 默认相冊的路径
    String path = photoDCIM + File.separator + date.getTime() + ".jpg"; 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path )));
    startActivityForResult(intent, PICTURE_CAMERA);

    上面带指定的保存路径path 。就是Camera中的mSaveUri

    所以结果就是Camera仅仅会返回RESULT_OK

    结论

    我们调用Camera能够有2种方式获得拍照的图片:


    第1种是指定保存路径。

    如上面的演示样例代码,将path设置为成员变量,在onActivityResult()中,直接读取该值就可以。

    第2种是不指定保存路径。

    调用方法例如以下:

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    getActivity().startActivityForResult(intent, PICTURE_CAMERA);

    onActivityResult

    Bitmap bitmap= data.getParcelableExtra("data");  

    这样就能得到拍照的图片了。

    总结

    在日常使用过程中,推荐使用指定保存路径。这样能够方便获得File,然后做其它的操作。

  • 相关阅读:
    【提高组】
    【学习】数论
    【2019.10.2】NOIP2018 模拟赛
    【普及组BOSS】
    ELK搭建elasticsearch常见报错
    Linux 下 安装Python第三方模块工具箱pip,以及用pip安装的方法
    Centos 基本命令不能用恢复方法
    Docker0 网卡删除
    Tomcat 设置开机自启
    Python 终端输出字体颜色
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/7211374.html
Copyright © 2020-2023  润新知