[英]How to load image from url
我正在为Android编写一个小相框应用程序,它使用opengl作为部分UI。 这部分需要从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()方法来支持具有逻辑意义的内容?
我正在不在模拟器中的三星银河选项卡上进行测试
我认为您应该实现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);
}
}
希望对您有帮助!
这似乎不太理想,但是如果您将字节流逐字节读取到缓冲区中,然后将字节数组传递给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(bytes,0,fileLength)一次将字节读取到缓冲区中,但是除非我在调用read之前稍等片刻,否则它无法可靠地完全填充缓冲区。 android的InputStream的read方法的实现是否有缺陷,导致BitmapFactory的encodeStream方法由于数据不完整而失败?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.