BitmapFactory解码流在使用输入流读取时返回null

时间:2017-07-25 09:14:55

标签: android bitmap

我有两个案例

第一个案例

在这种情况下,图像显示但进度对话框未显示

URL url = new URL(params[0]);
connection = (HttpsURLConnection) (url.openConnection());
connection.setRequestMethod("GET");
connection.connect();

int fileSize = connection.getContentLength() / 1000;

stream = connection.getInputStream();
image = BitmapFactory.decodeStream(stream);


  while((b = stream.read(data))!=-1)
  {
     total += b / 1000;
     publishProgress(String.valueOf(total)+" kb / "+String.valueOf(fileSize)+"kb");
  }


return image;

日志

D/ImageDownload: doInBackground: android.graphics.Bitmap@efb3c21

第二种情况 在这种情况下,显示进度对话框但图像未显示

URL url = new URL(params[0]);
connection = (HttpsURLConnection) (url.openConnection());
connection.setRequestMethod("GET");
connection.connect();

int fileSize = connection.getContentLength() / 1000;

stream = connection.getInputStream();

while((b = stream.read(data))!=-1)
{
    total += b / 1000;
    publishProgress(String.valueOf(total)+" kb / "+String.valueOf(fileSize)+"kb");
}

image = BitmapFactory.decodeStream(stream);
Log.d(TAG, "doInBackground: "+String.valueOf(image));


return image;

日志

D/ImageDownload: doInBackground: null

1 个答案:

答案 0 :(得分:0)

我在经历了3个小时的挣扎之后做到了

使用 ByteArrayOutputStream

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte []data = new byte[1024];
  int b;
   while((b = stream.read(data))!=-1)
   {
      total += b / 1000;
      publishProgress(String.valueOf(total)+" kb / "+String.valueOf(fileSize)+"kb");
      bos.write(data,0,b);
    }

byte []data = new byte[1024]
InputStream in = new ByteArrayInputStream(content);
image = BitmapFactory.decodeStream(in);