4

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?

Thanks in advance, will highly appreciate any kind of help.

4

2 回答 2

8

我不确定您是否可以从下载中明确构建 png。但是,这是我用来下载图像并将它们显示到 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;
    }
}

然后,创建一个 BitMap 并将其关联到 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();
于 2010-07-28T09:22:01.313 回答
4

您可以从下载中明确构建 png。

bm.compress(Bitmap.CompressFormat.PNG, 100, out);

100是您的压缩率(PNG 通常是无损的,因此 100%)

out是您要将 png 保存到的文件的 FileOutputStream。

于 2011-03-23T15:46:39.687 回答