Android:如何使用Async下载.png文件并将其设置为ImageView?

6
我有一张.png图片的URL需要下载,并将其设置为ImageView的来源。我是一个初学者,有几个问题不明白: 1)我应该把文件存储在哪里? 2)如何在Java代码中将其设置为ImageView? 3)如何正确地重写AsyncTask方法?
谢谢提前,非常感谢任何形式的帮助。
2个回答

8

我不确定您是否可以直接从下载构建一个png。但是这是我用来下载图像并将其显示在ImageView中的方法:

首先,您需要下载图像:

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关联:
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);

这就是全部内容。
编辑: 实际上,您可以通过以下方式保存文件:
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();

它为我引发了一个异常 抛出了类型为 'Android.OS.NetworkOnMainThreadException' 的异常。 - Windgate

5
你可以从下载中显式构建一个png。
bm.compress(Bitmap.CompressFormat.PNG, 100, out);

100 是你的压缩比(PNG通常是无损压缩,所以为100%)

out 是你要保存PNG文件的FileOutputStream。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接