【问题标题】:How to get InputStream back from String如何从字符串中取回 InputStream
【发布时间】:2014-03-21 05:03:04
【问题描述】:

有一个场景,httpentity 在 InputStream 中有图像的二进制数据,为了进一步处理,它被转换为库文件中的字符串[String str = EntityUtils.toString(httpResponse.getEntity())],现在我试图从该字符串中取回输入流。

请看下面的场景来理解问题:

Working - ImageView 显示内容

InputStream inStream = getContentResolver().openInputStream(thisPhotoUri);
Bitmap bm = BitmapFactory.decodeStream(inStream);
ImageView view = (ImageView)findViewById(R.id.picture_frame);
view.setImageBitmap(bm);

问题 - ImageView 不显示图像

InputStream inStream = getContentResolver().openInputStream(thisPhotoUri);
String str = inStream.toString();
InputStream is = new ByteArrayInputStream(str.getBytes());
Bitmap bm = BitmapFactory.decodeStream(is);
ImageView view = (ImageView)findViewById(R.id.picture_frame);
view.setImageBitmap(bm);

【问题讨论】:

    标签: java android inputstream raw-data httpentity


    【解决方案1】:

    InputStream.toString() 不符合您的预期。它将调用Object.toString() 方法,你会得到类似java.io.InputStream@604c9c17 的东西,而不是流的真实内容!

    试试System.out.println(str);看看,它的价值是什么。

    这就是为什么你不能从这个内容重新生成原来的InputStream,因为它不是InputStream的内容!

    您必须以另一种方式读取流才能将内容发送到String!见:Read/convert an InputStream to a String

    【讨论】:

      【解决方案2】:

      您不能直接将 InputStream 转换为 String。这可能是问题所在。

      String str = inStream.toString();
      

      Take a look at this标识InputStream转String的方式。

      【讨论】:

      • 尝试了链接中提到的字符串转换,当我将字符串转换回流并将其传递给位图工厂时,它仍然返回 null。
      • 为什么要将输入流转换为字符串,您是否对其进行了任何修改?
      • Http 调用在 jar 文件中完成,响应以 json 形式返回,因此在这种情况下,流(图像二进制)被转换为字符串并添加到 json,应用层现在尝试使用字符串取回流并获取图像。
      【解决方案3】:

      这应该是你要找的:

      InputStream stream = new ByteArrayInputStream(yourString.getBytes("UTF-8"));

      【讨论】:

      • 试过了,没用。由于Bitmapfactory在传递流时返回null。
      猜你喜欢
      • 1970-01-01
      • 2011-10-12
      • 2011-08-08
      • 2012-02-18
      • 1970-01-01
      • 2012-12-25
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多