2013-03-21 109 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字符串作爲