【问题标题】:Android/Java - How to retrieve image from web service and show itAndroid/Java - 如何从 Web 服务中检索图像并显示它
【发布时间】:2012-08-22 01:16:33
【问题描述】:

我正在使用通常返回 JSON 响应的 Web 服务的某些服务,但是当我发送用户 ID 时,一项服务返回静态 GIF 图像(非动画)。

我正在做的程序是:

1.使用 DefaultHttpClient 连接到 Web 服务
2.使用此实用方法将接收到的InputStream转换为String:

public static String inputStreamToStringScanner(InputStream in) {

  Scanner fileScanner = new Scanner(in);
  StringBuilder inputStreamString = new StringBuilder();
  while(fileScanner.hasNextLine())
    inputStreamString.append(fileScanner.nextLine()).append("\n");
  fileScanner.close();

  return inputStreamString.toString();
}

3.存储转换后接收到的String,用于处理服务器响应。

对于图像服务,当我看到转换后的字符串时,它的开头是这样的: “GIF89a?��?�� ...”

这是一个静态 GIF 文件。

我无法在 ImageView 中显示图像,我尝试了在网络上找到的不同方法:

public void onPhotoFinished (String responseData) {

  InputStream is = new ByteArrayInputStream(responseData.getBytes());
  Bitmap bm = BitmapFactory.decodeStream(is);
  userImage.setImageBitmap(bm);
}

这是我也尝试过的其他方法:

public void onPhotoFinished (String responseData) {

  InputStream is = new ByteArrayInputStream(responseData.getBytes());
  final Bitmap bm = BitmapFactory.decodeStream(new BufferedInputStream(is));
  userImage.setImageBitmap(bm);
}

这也不起作用:

public void onPhotoFinished (String responseData) {

  InputStream is = new ByteArrayInputStream(responseData.getBytes());
  Drawable d = Drawable.createFromStream(is, "src name");
  userImage.setImageDrawable(d);
}

最后,这也不起作用:

public void onPhotoFinished (String responseData) {

  Bitmap bm = BitmapFactory.decodeByteArray(responseData.getBytes(), 0, responseData.getBytes().length);
  userImage.setImageBitmap(bm);
}

在 Logcat 中,我收到“decoder->decode returned false”

似乎没有任何效果...有什么问题的想法吗?

谢谢!

【问题讨论】:

  • 您肯定应该为图像数据使用二进制数据结构,而不是字符串?此外,如果它是 gif,那么您将需要一个上帝解码器 - 谷歌。
  • Gif 解码器 - 该死的 iPhone 自动更正
  • 您是说 BitmapFactory.decode 不适用于 GIF 文件吗?这是一个静态的gif。谢谢你的回答。

标签: java android


【解决方案1】:

最后,我用 FlushedInputStream 解决了,直接使用 Input Stream,避免了转换成字符串:

static class FlushedInputStream extends FilterInputStream { 

public FlushedInputStream(InputStream inputStream) {
    super(inputStream);
}

@Override
public long skip(long n) throws IOException { 

  long totalBytesSkipped = 0L;
  while (totalBytesSkipped < n) { 
    long bytesSkipped = in.skip(n - totalBytesSkipped);
    if (bytesSkipped == 0L) { 
      int byteReaded = read();
      if (byteReaded < 0) {
          break; 
      } else {
          bytesSkipped = 1;
      }
    }
    totalBytesSkipped += bytesSkipped;
  }
  return totalBytesSkipped;
}

}

与:

Bitmap bitmapResponseData = BitmapFactory.decodeStream(new FlushedInputStream(is));

问候

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    相关资源
    最近更新 更多