【问题标题】:Why does Bitmap.compress() return false when writing to internal storage?为什么 Bitmap.compress() 在写入内部存储时返回 false?
【发布时间】:2018-06-14 17:15:47
【问题描述】:

我修改了一些代码以将位图写入内部存储 (Android),该内部存储 (Android) 之前已成功写入外部存储。但是 compress() 现在返回 false。不幸的是,文档没有描述可能导致这种情况的条件,当然,由于没有抛出异常,因此没有任何帮助。

下面是我的代码。

// Only change made was to the line immediately below, now commented out 
// File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/AIL_SCANS"); //Creates app specific folder

        File directory = contextIn.getDir("my_pics", Context.MODE_PRIVATE);
        if (!directory.exists())
            directory.mkdirs();

        File file = new File(directory, sFilenameIn + ".jpg");

        FileOutputStream os = new FileOutputStream(file);
        if (!imageIn.compress(Bitmap.CompressFormat.JPEG, 100, os))
            Log.e("Error", "     compress() failed (returned false)");

        os.flush();
        os.getFD().sync();
        os.close();
        Log.e("Success", "     Profit!!");

我的代码将位图创建为 ARGB_8888(见下文),因此报告类似故障的其他几个 Stack Overflow 帖子似乎不适用于此处。

bmp = Bitmap.createBitmap(arrPixels, widh, height, Bitmap.Config.ARGB_8888);

一些显然对大量 Stack Overflow 用户运行良好的代码示例与我的几乎一模一样。 Saving and Reading Bitmaps/Images from Internal memory in Android

【问题讨论】:

  • 您请求权限了吗?您运行的是哪个版本的 Android?
  • 我正在运行 7.0
  • 没有WRITE_INTERNAL_STORAGE 权限。 LogCat 是否显示任何内容?
  • @CommonsWare,没有 LogCat 什么也没有显示。它只是失败了。
  • 嗯...尝试使用compress()ByteArrayOutputStream。如果它也返回false,则表明Bitmap 有一些奇怪的地方(例如,它使用 alpha 通道,而 JPEG 不支持透明度)。或者,尝试将 compress() 转换为 PNG 文件,看看是否可行。

标签: android bitmap fileoutputstream internal-storage android-internal-storage


【解决方案1】:

如果您运行的是 Android 6.0 >= 您必须在写入存储之前请求权限。

请参阅此文档Ask for permissions

【讨论】:

  • 不适用于内部存储。
  • 我不认为我必须请求内部存储的许可,但我打算试一试。
猜你喜欢
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2013-09-18
  • 1970-01-01
  • 2011-05-22
  • 2014-11-17
  • 2014-03-11
相关资源
最近更新 更多