0

我根据一个url返回一个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

然后我把它保存到sdcard。保存图片就OK了。

现在的问题是使用这个url访问时会下载图片A。但它现在在 SDCARD 中显示了另一张 B 图片。如何解决这个问题?</p>

4

1 回答 1

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 作为字符串

于 2013-03-21T08:45:21.627 回答