问题描述
我有一个的PNG图片,需要下载并设置为ImageView的源的URL。我是个初学者,到目前为止,所以有一些事情我不明白:1)我在哪里存储文件?2)如何设置它在Java code ImageView的?3)如何正确地重写AsyncTask的方法?
I've got the URL of a .png image, that needs to be downloaded and set as a source of an ImageView. I'm a beginner so far, so there are a few things I don't understand:1) Where do I store the file?2) How do I set it to the ImageView in java code?3) How to correctly override the AsyncTask methods?
在此先感谢,将高度AP preciate任何形式的帮助。
Thanks in advance, will highly appreciate any kind of help.
推荐答案
我不知道,你可以明确地从下载建立一个PNG。然而,这里是我用它来下载图片,并显示他们到Imageviews:
I'm not sure you can explicity build a png from a download. However, here is what I use to download images and display them into Imageviews :
首先,你下载的图片:
protected static byte[] imageByter(Context ctx, String strurl) {
try {
URL url = new URL(urlContactIcon + strurl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
然后,创建一个位图和它关联到ImageView的:
And then, create a BitMap and associate it to the Imageview :
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);
这就是它。
修改
其实,你可以通过这样保存文件:
EDIT
Actually, you can save the file by doing this :
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();
这篇关于Android的:如何使用异步下载一个PNG文件并将其设置为ImageView的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!