首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BitmapFactory解码问题

BitmapFactory解码问题
EN

Stack Overflow用户
提问于 2013-09-15 17:09:29
回答 1查看 499关注 0票数 1
代码语言:javascript
复制
url="http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/ladee_spin_2_in_motion_0_0.jpg?itok=yNhf69rE";

 try { 
                HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                return bitmap;
            } 
            catch (Exception e) 
            { 
                e.printStackTrace(); 
                return null;
            }

我试图从url中检索图片,但不管怎样,它总是返回null。在调试模式下,我观察到它在尝试input.close();时发生。我怎么可能得到图像。

EN

回答 1

Stack Overflow用户

发布于 2013-09-15 17:16:21

这是加载位图的正确方法:

代码语言:javascript
复制
    InputStream is;
    Bitmap bitmap;
    is = context.getResources().openRawResource(DRAW_SOURCE);


    bitmap = BitmapFactory.decodeStream(is);
    try {
        is.close();
        is = null;
    } catch (IOException e) {
    }

然而,正如我所看到的,你在解码之前关闭了流。

如果是,请使用其他方法:

代码语言:javascript
复制
Bitmap bitmap;
InputStream input = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input, 8192);

ByteArrayBuffer buff = new ByteArrayBuffer(64);
int current = 0;
while ((current = bis.read()) != -1) {
    buff.append((byte)current);
 }

  byte[] imageData = buff.toByteArray();
  bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

  try {
        is.close();
        is = null;
    } catch (IOException e) {
    }

顺便说一句,参见this post,它也应该可以工作

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18810728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档