1
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(); 时发生。. 我怎么可能得到图像。

4

1 回答 1

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) {
    }

顺便说一句,看到这个帖子,它也应该工作

于 2013-09-15T09:16:20.917 回答