【问题标题】:How to convert image file data to a Bitmap?如何将图像文件数据转换为位图?
【发布时间】:2016-08-24 10:51:34
【问题描述】:
 URL imageUrl = new URL("http://192.168.0.103:8080/mm/showImage?id=2&fileName=fesc1cc.JPG&imgType=books" );

        //URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl
                .openConnection();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        StringBuffer buffer = new StringBuffer();
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            buffer.append(inputLine);
        in.close();     


        conn.getResponseCode();
        System.out.println(conn.getResponseCode());
        System.out.println(buffer.toString());
        conn.disconnect();

如何将收到的数据转换为位图并在图像视图中显示。

【问题讨论】:

标签: android bitmap android-bitmap


【解决方案1】:
byte[] imageAsBytes = Base64.decode(myImageData.getBytes());
Bitmap bp = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);

byte []bt = buffer.toString().getBytes();
Bitmap i = BitmapFactory.decodeByteArray(buffer.getBytest or buffer.tobytes, 0,bt.length);

【讨论】:

  • 数据在StringBuffer缓冲区中,我是否必须将其转换为字符串。@SuhasBachewar
  • @ShwetabhSingh 您必须编写“ buffer.toString() ”或直接传递缓冲区数据作为更新答案中的提及
  • 这里的 bt.length 是什么@SuhasBachewar
【解决方案2】:

你可以使用毕加索库来做到这一点Picasso.with(context).load(imageUrl).into(imageview);

【讨论】:

  • 请为您的答案添加一些解释。在 SO 上不鼓励仅使用代码回答。
【解决方案3】:

改用毕加索图书馆。毕加索非常容易使用。 Picasso.with(context).load("url").into(ImageView)。 更多信息在这里 http://square.github.io/picasso

【讨论】:

    【解决方案4】:

    更有效的方法是使用 Glide。 Glide 是一个快速高效的 Android 开源媒体管理和图像加载框架,它将媒体解码、内存和磁盘缓存以及资源池封装到一个简单易用的界面中。

    库的使用:

    • 将以下代码添加到您的 gradle 文件 (Module:app)

      repositories {
          mavenCentral() 
      }
      
      dependencies {
          ...
          compile 'com.github.bumptech.glide:glide:3.7.0'
      }
      
    • 使用 glide 将你的 url 图片加载到 imageview

      Glide.with(this).load(imageUrl).into(imageView);
      

    欲了解更多信息,请访问https://github.com/bumptech/glide

    祝你好运。

    编辑:

    Glide.with(this)
    .load("http://192.168.0.103:8080/mm/showImage?id=2&fileName=fesc1cc.JPG&imgType=books")
    .into(imageView);
    

    【讨论】:

    • 是否也转换原始数据
    • 是的,您可以使用 Glide 加载图像的字节数组,但我想您想从 url 加载图像?您无需打开连接并获取流。 Glide 可以处理,只要给它 imageUrl 和 imageview 就可以了。
    • 我必须发送一些参数并从 URL 获取原始数据,然后将其转换为位图 @BatuhanCoskun
    • 在 imageView 中没有得到任何东西。@BatuhanCoskun
    猜你喜欢
    • 1970-01-01
    • 2012-07-28
    • 2011-11-29
    • 2016-08-16
    • 2012-03-11
    • 2019-08-05
    • 2014-01-26
    • 2015-02-17
    相关资源
    最近更新 更多