【问题标题】:Android IOException when compressing a Bitmap压缩位图时出现Android IOException
【发布时间】:2013-06-01 07:01:44
【问题描述】:

在我的 Android 项目中,我试图将位图保存到给定位置的 SD 卡。

当我运行这个时,我每次都会收到一个IOException,说权限被拒绝。这是关于创建 FileOutputStream。

这让我相信我缺少权限,但我包含了READ and WRITE_EXTERNAL_STORAGE。它们在我的 uses-sdk 块之前声明并且在应用程序块之外。我还将 read/write 文本发送到我的应用程序其他地方的文件中,并且效果很好。我当前的代码被修改以匹配我在网上找到的几个解决方案,但我无法成功保存bitmap 文件。

如果有人能指出我的错误,我将非常感激。

    ImageView imageView = (ImageView) findViewById(R.id.new_pnm_pic);
    Bitmap bm = (Bitmap)data.getExtras().get("data");
    imageView.setImageBitmap(bm);
    String outPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recruits";

    try {
          File d = new File(outPath);
          if (!d.exists())
          d.mkdirs();

          SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
          String currentTime = sd.format(new Date());

          File file = new File(outPath+'/'+currentTime+".jpg");             
          FileOutputStream fOut = new FileOutputStream(file.getPath());

          bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut);

          fOut.flush();
          fOut.close();

       }
   catch(IOException ioe){
     Toast.makeText(this, "Nice try but didn't work", Toast.LENGTH_SHORT).show();
        }

【问题讨论】:

  • 如果你用 Environment.getExternalStorageDirectory().toString() + "Recruits" 定义你的 outPath 是否有效?我对 getAbsolutePath() 有类似的问题,解决了它。做一个日志。在 logcat 中查看完整路径。
  • 你是在模拟器上运行的吗
  • 我把 outPath 改成了 Environment.getExternalStorageDirectory().toString() + "/Recruits";并使用 Logs 进行测试以查看我的文件使用以下路径 W//mnt/sdcard/Recruits/2013-06-01-17-26-50.jpg(23309) 当我在创建 FileOutputStream 后尝试测试时,日志没有显示,这意味着这是异常所在。我还尝试使用备用构造函数 FileOutputStream(File) ,但仍然出现异常。山姆:我在我的设备上运行这个
  • 我也刚刚发现了如何检查异常消息并用它来确定问题是“权限被拒绝”,但我在程序的其他地方读/写文本文件,效果很好

标签: android file-io bitmap compression ioexception


【解决方案1】:

改变这个

File file = new File(outPath+'/'+currentTime+".jpg");


收件人

File file = new File(d+'/'+currentTime+".jpg");

并为清单文件添加权限:-

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

编辑
在我们开始将图像保存到 sd 卡之前,我们需要检查 sd card is mounted or not 是否。

【讨论】:

  • 我尝试了 File 的替代构造函数,它没有改变任何东西。我的权限也很好,它们已经过检查,我在我的应用程序的其他部分读/写外部存储没有错误。
  • 把 file.getPath() 改成 file.getAbsolutePath()
猜你喜欢
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2016-04-16
  • 2015-04-23
相关资源
最近更新 更多