【问题标题】:Android: How to download a .png file using Async and set it to ImageView?Android:如何使用 Async 下载 .png 文件并将其设置为 ImageView?
【发布时间】:2011-03-22 00:37:53
【问题描述】:

我有一个 .png 图像的 URL,需要下载并设置为 ImageView 的源。到目前为止我是初学者,所以有一些我不明白的事情: 1)我在哪里存储文件? 2) 如何在 java 代码中将其设置为 ImageView? 3) 如何正确覆盖 AsyncTask 方法?

在此先感谢,非常感谢任何形式的帮助。

【问题讨论】:

    标签: android png android-asynctask


    【解决方案1】:

    我不确定您是否可以明确地从下载中构建 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();
    

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2011-09-13
        • 2015-05-27
        • 1970-01-01
        • 2021-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        相关资源
        最近更新 更多