android图片下载

时间:2013-03-21 08:36:19

标签: android bitmap

我根据网址返回一个Bitmap对象,以及下载图片的代码:

URL url = new URL(imageUrlStr);
       URLConnection conn = url.openConnection();
       conn.setDoInput(true);
       conn.connect();
       InputStream in = conn.getInputStream();
       Bitmap bitmap = BitmapFactory.decodeStream(in);
           in.close

然后我把它保存到SD卡。保存图片是可以的。

现在问题是当使用此网址访问时下载图片A.但它现在显示了SDCARD中的另一张B画面。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以通过哈希码识别图像。不是一个完美的解决方案,适合演示

 private Bitmap getBitmap(String url) {
                String filename = String.valueOf(url.hashCode());
                File f = new File(cacheDir, filename);
                // from SD cache
                Bitmap b = decodeFile(f);
                if (b != null)
                    return b;
                // from web
                try {
                    Bitmap bitmap = null;
                    InputStream is = new URL(url).openStream();
                    OutputStream os = new FileOutputStream(f);
                    CopyStream(is, os);
                    os.close();
                    bitmap = decodeFile(f);
                    return bitmap;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return null;
                }
            }

        private void CopyStream(InputStream is, OutputStream os) {
                    final int buffer_size = 1024;
                    try {
                        byte[] bytes = new byte[buffer_size];
                        for (;;) {
                            int count = is.read(bytes, 0, buffer_size);
                            if (count == -1)
                                break;
                            os.write(bytes, 0, count);
                        }
                    } catch (Exception ex) {
                    }
                }

/** decodes image and scales it to reduce memory consumption*/
    private Bitmap decodeFile(File f) {
        try {

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPurgeable = true;
            return BitmapFactory.decodeStream(new FileInputStream(f));

        } catch (FileNotFoundException e) {
        }
        return null;
    }

使用你只需要使用方法“getBitmap(String)”和你想要的url作为String

相关问题