【问题标题】:BitmapFactory decode issueBitmapFactory 解码问题
【发布时间】:2013-09-15 09:09:28
【问题描述】:
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(); 时发生。 . 我怎么可能得到图像。

【问题讨论】:

    标签: android bitmapfactory


    【解决方案1】:

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

        InputStream is;
        Bitmap bitmap;
        is = context.getResources().openRawResource(DRAW_SOURCE);
    
    
        bitmap = BitmapFactory.decodeStream(is);
        try {
            is.close();
            is = null;
        } catch (IOException e) {
        }
    

    但是,我看到您在完成解码之前关闭了流。

    如果是这样,请使用其他方式:

    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,它应该也可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多