如何从网址加载图片

问题描述:

我正在为使用opengl作为UI部分的android编写一个小图片框架应用程序。这部分需要从flickr获取图像并将其加载到纹理中。我有下面的代码是功能性的大部分时间,但它有一个Thread.sleep()方法杂牌在得到从这个连接的输入流和位图工厂流解码之间:如何从网址加载图片

  URL url = new URL("http://farm5.static.flickr.com/4132/5168797476_7a85deb2be_b.jpg"); 
      URLConnection con = url.openConnection(); 
      InputStream is = con.getInputStream(); 
      Thread.sleep(250); //What am I actually waiting for? 
      sourceBitmap = BitmapFactory.decodeStream(is); 

如何获得围绕使用sleep()方法来支持某些具有逻辑意义的东西?

我测试三星Galaxy Tab上不是在模拟器

这看起来不太理想,但是如果您将字节逐字节读入缓冲区,然后将字节数组传递给BitmapFactory,则它可以正常工作。

  URL url = new URL("http://farm5.static.flickr.com/4132/5168797476_7a85deb2be_b.jpg"); 
      URLConnection con = url.openConnection(); 
      con.connect(); 
      int fileLength = con.getContentLength(); 
      InputStream is = con.getInputStream(); 
      byte[] bytes = new byte[fileLength]; 
      for(int i=0;i<fileLength;i++) { 
       bytes[i] = (byte)is.read(); 
      } 
      sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, fileLength); 

我试着用is.read读取的字节到缓冲区中一次全部(字节,0,文件长度),但它并没有可靠的完全填充缓冲,除非我调用read前等了一会儿。 InputStream的read方法的android实现有可能存在缺陷,导致BitmapFactory的decodeStream方法由于不完整的数据而失败?

我想你应该实现AsyncTask。请参考:http://developer.android.com/resources/articles/painless-threading.html

public void onClick(View v) { 
    new DownloadImageTask().execute("http://example.com/image.png"); 
} 

private class DownloadImageTask extends AsyncTask<string, void,="" bitmap=""> { 
    protected Bitmap doInBackground(String... urls) { 
     return loadImageFromNetwork(urls[0]); 
    } 

    protected void onPostExecute(Bitmap result) { 
     mImageView.setImageBitmap(result); 
    } 
} 

我希望它可以帮助你!

+0

异步下载图像当然是一个好主意,但是,它并没有真正解决实际问题 – 2010-12-02 03:41:35