如何加载从URL图像 [英] How to load image from url
问题描述
我写了一个使用OpenGL进行了UI的一部分机器人有点相框应用程序。这部分需要从Flickr获取图像并将其加载到纹理。的code口有下面是功能的大部分时间,但它有一个Thread.sleep()方法组装机在获得从连接的输入流和所述位图工厂的流进行解码之间:
I am writing a little picture frame app for android that is using opengl for part of the UI. This portion needs to get images from flickr and load them into a texture. The code I have below is functional most of the time, but it has a Thread.sleep() kludge in between getting the input stream from the connection and the bitmap factory decoding the stream:
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()方法有利于东西,让逻辑意义身边?
How do I get around using the sleep() method in favor of something that makes logical sense?
我测试三星Galaxy Tab上不是在模拟器
I am testing on a samsung galaxy tab not in the emulator
推荐答案
这似乎不太理想,但如果你读出字节流字节到缓冲区中,然后通过字节数组BitmapFactory它工作正常。
This seems less than ideal, but if you read the stream byte by byte into a buffer and then pass the byte array to the BitmapFactory it works correctly.
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方法是有缺陷造成BitmapFactory的德codeStream方法失败是由于不完整的数据?
I tried reading the bytes into the buffer all at once with is.read(bytes, 0, fileLength) but it did not reliably fill the buffer completely unless I waited a moment before calling the read. Is it possible that android implementation of InputStream's read method is flawed causing the BitmapFactory's decodeStream method to fail due to incomplete data?
这篇关于如何加载从URL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!