使用循环从 url 加载图像
我使用这段代码从服务器下载图像:
public Bitmap getBitmap(String path){
URL url=new URL(path);
URLConnection connection=url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap bmp=BitmapFactory.decodeStream(is);
return bmp;
}
它对于 1 个图像工作正常,但如果我在循环、第二次、第三次等迭代中使用它,它会返回一些奇怪的东西(位图的 mWidth
和mHeight
字段为 -1
)。 问题出在哪里?
(第二次、第三次等迭代的路径
都很好,我检查了这一点)
编辑
循环示例:
//images - is a String array
for(int i=0; i<images.length(); i++){
Bitmap bmp=getBitmap(images[i]);
}
Ss you可以看到,这个周期没有什么异常
I'm using this code for downloading image from server:
public Bitmap getBitmap(String path){
URL url=new URL(path);
URLConnection connection=url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap bmp=BitmapFactory.decodeStream(is);
return bmp;
}
It works fine for 1 image, but if I'm using this in cycle, on second, third etc iterations it returns something strange (Bitmap's mWidth
and mHeight
fields are -1
). Where can be the problem?
(path
on second, third etc. iterations are fine, I checked this)
EDIT
Example of cycle:
//images - is a String array
for(int i=0; i<images.length(); i++){
Bitmap bmp=getBitmap(images[i]);
}
Ss you can see, there is nothing unusual in this cycle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在完成一个位图之后、加载下一个位图之前调用
Bitmap.recycle
。问题是,即使可能也无济于事 - 位图无法自行调整大小。
也许,最好制作一组位图 - 一个永远的路径。
恐怕,由于优化,java机器(或编译器)不会破坏以前的位图,而是尝试重用它。请在这里写下结果。这很有趣。
尝试读取图像的大小而不是读取它们:
在此之后使用下面的代码来获取高度和宽度:
你看到了什么?
尝试更改路径的顺序 - 再次只有第一个就可以了吗?如果不是,则问题出在文件上。如果是,则在连接/流/工厂中。
Try calling
Bitmap.recycle
after you've finished with one Bitmap but before you load the next.The problem is, that even than maybe won't help - Bitmaps can't resize themselves.
Maybe, better make array of bitmaps - one for ever path.
I am afraid, that java machine (or compiler) due to optimization doesn't destroy the previous bitmap, but tries to reuse it. Please, write here about results. It is interesting.
try to read the size of images not reading them:
after this use below code to get height and width:
What do you see?
Try to change the order of the paths - again only the first will be OK? If not, the problem is in files. If yes, in connection/stream/factory.