来自 BitmapFactory 的损坏图像

Corrupted Images From BitmapFactory

有时候我在下载图片的时候,有些图片会出现灰线,如下图示例所示:

这往往只发生在网络状况不佳的情况下。

我的图像解码代码本质上是 UIL 代码的修改版本:

Bitmap decodedBitmap = BitmapFactory.decodeStream(stream, null, decodingOptions);

其中流只是远程文件的 InputStream

现在我在 Google Play Music 应用程序上看到了这种行为,这让我想知道这是否是 BitmapFactory 的问题。 到目前为止我想出的唯一解决方案可能是进行校验和比较以确保下载了整个图像。

编辑:

HttpURLConnection conn = getConnection(path);
InputStream inputStream = conn.getInputStream()
stream = new ContentLengthInputStream(new BufferedInputStream(download, BUFFER_SIZE), conn.getContentLength())

已通过以下步骤解决:

  • 正常打开图像的InputStream
  • 将流写入 ByteArrayOutputStream
  • 将 ByteArrayOutputStream 的长度与来自 HttpURLConnection
  • 的 Content-Length header 进行比较
  • 如果不匹配,则表示您在传输过程中丢失了数据
  • 否则,您可以将 ByteArrayOutputStream 转换为 ByteArrayInputStream 并根据需要与 BitmapFactory 一起使用