我看到了这个问题:android如何下载一个1MB的图像文件并将其设置为ImageView
它没有解决我的问题,因为它只展示了如何在你已经拥有图片后显示位图。
我正在尝试从URL下载一张图片,并在Android设备上用ImageView显示它。我不确定该怎么做。
我在互联网上查找了一些资料,这是我到目前为止的代码:
它没有解决我的问题,因为它只展示了如何在你已经拥有图片后显示位图。
我正在尝试从URL下载一张图片,并在Android设备上用ImageView显示它。我不确定该怎么做。
我在互联网上查找了一些资料,这是我到目前为止的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set local image
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);
//Prepare to download image
URL url;
InputStream in;
//BufferedInputStream buf;
try {
url = new URL("http://i.imgur.com/CQzlM.jpg");
in = url.openStream();
out = new BufferedOutputStream(new FileOutputStream("testImage.jpg"));
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
out.close();
in.close();
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}