2013-03-21 188 views
0

我根据URL返回一个位图对象,并下载图片代码:安卓图片下载

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卡。可以保存图片。

现在的问题是它下载图片时使用此URL来访问。但它现在在SDCARD中显示另一张B图片。如何解决这个问题?

回答

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(字符串)”与您所需的URL字符串作为