2014-04-30 61 views
2

我使用通用圖像加載程序庫從網絡異步加載圖像。使用通用圖像加載程序緩存沒有顯示的圖像

我想將圖像存儲在磁盤緩存中而不顯示它們,以便即使用戶變爲脫機狀態,圖像在必要時仍可在本地使用。

那麼,如何將圖像保存在緩存中而不顯示它們呢?

我已經試過這一點,但似乎不工作:

DisplayImageOptions opts = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build(); 
ImageLoader.getInstance().loadImage(url, opts, null); 
+0

你可以編寫你自己的類,只需創建一個內存緩存類,該類包含Map中的字符串id和位圖,只需放置並獲取操作即可。 fileCache的另一個類,它將在緩存目錄上創建一個文件。然後只需寫入裝載機類,它將從網上下載圖像並在磁盤上執行它們。 – NaserShaikh

回答

-1

通用圖像裝載機庫的主要思想是圖像的異步下載和顯示他們內部查看。兌現是圖書館的功能之一。如果您需要緩存圖像而不顯示它們,則不應使用通用圖像加載程序。只需編寫一個簡單的AsyncTask類,即可將圖像下載到磁盤。 下面是下載圖像的函數示例,只需在您的AsyncTask的doInBackGround中爲要下載的所有圖像調用它即可。

private void downloadImagesToSdCard(String downloadUrl,String imageName) 
{ 
try 
{ 
     URL url = new URL(downloadUrl); //you can write here any link 

    File myDir = new File("/sdcard"+"/"+Constants.imageFolder); 
    //Something like ("/sdcard/file.mp3") 


    if(!myDir.exists()){ 
     myDir.mkdir(); 
     Log.v("", "inside mkdir"); 

    } 

    Random generator = new Random(); 
    int n = 10000; 
    n = generator.nextInt(n); 
    String fname = imageName; 
    File file = new File (myDir, fname); 
    if (file.exists()) file.delete(); 

     /* Open a connection to that URL. */ 
     URLConnection ucon = url.openConnection(); 
     InputStream inputStream = null; 
     HttpURLConnection httpConn = (HttpURLConnection)ucon; 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
     inputStream = httpConn.getInputStream(); 
     } 

     /* 
     * Define InputStreams to read from the URLConnection. 
     */ 
     // InputStream is = ucon.getInputStream(); 
     /* 
     * Read bytes to the Buffer until there is nothing more to read(-1). 
     */ 

     FileOutputStream fos = new FileOutputStream(file); 
     int size = 1024*1024; 
     byte[] buf = new byte[size]; 
     int byteRead; 
     while (((byteRead = inputStream.read(buf)) != -1)) { 
      fos.write(buf, 0, byteRead); 
      bytesDownloaded += byteRead; 
     } 
     /* Convert the Bytes read to a String. */ 

     fos.close(); 

}catch(IOException io) 
{ 
    networkException = true; 
    continueRestore = false; 
} 
catch(Exception e) 
{ 
    continueRestore = false; 
    e.printStackTrace(); 
} 
} 
0

我已經使用了一個叫做鉭的庫。它是J2ME和Android的跨平臺庫。它具有出色的緩存機制。您可以將它用於您的應用程序。更多的細節可以AT-

https://github.com/TantalumMobile/Tantalum

0

找到您可以輕鬆地Picasso庫從廣場做到這一點:

Picasso.with(context) 
     .load(url) 
     .fetch(); 

這個代碼簡單的下載和不顯示它緩存圖像。

+0

畢加索的問題是,如果用戶處於脫機狀態,則不會從磁盤加載映像。例如:'Picasso.with(ctx).load(url).placeholder(R.drawable.my_placeholder).into(imageView)'它顯示佔位符,即使圖像在磁盤緩存中:( –

相關問題