【发布时间】:2011-12-07 23:12:17
【问题描述】:
我看过这个问题:android how to download an 1mb image file and set to 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());
}
}
【问题讨论】:
-
如果你找到了答案,你应该接受它。这样,其他用户就知道它有效。祝你好运!
标签: android download android-imageview