使用通用图像加载程序缓存没有显示的图像
问题描述:
我使用通用图像加载程序库从网络异步加载图像。使用通用图像加载程序缓存没有显示的图像
我想将图像存储在磁盘缓存中而不显示它们,以便即使用户变为脱机状态,图像在必要时仍可在本地使用。
那么,如何将图像保存在缓存中而不显示它们呢?
我已经试过这一点,但似乎不工作:
DisplayImageOptions opts = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
ImageLoader.getInstance().loadImage(url, opts, null);
答
通用图像装载机库的主要思想是图像的异步下载和显示他们内部查看。兑现是图书馆的功能之一。如果您需要缓存图像而不显示它们,则不应使用通用图像加载程序。只需编写一个简单的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();
}
}
答
我已经使用了一个叫做钽的库。它是J2ME和Android的跨平台库。它具有出色的缓存机制。您可以将它用于您的应用程序。更多的细节可以AT-
答
+0
毕加索的问题是,如果用户处于脱机状态,则不会从磁盘加载映像。例如:'Picasso.with(ctx).load(url).placeholder(R.drawable.my_placeholder).into(imageView)'它显示占位符,即使图像在磁盘缓存中:( –
你可以编写你自己的类,只需创建一个内存缓存类,该类包含Map中的字符串id和位图,只需放置并获取操作即可。 fileCache的另一个类,它将在缓存目录上创建一个文件。然后只需写入装载机类,它将从网上下载图像并在磁盘上执行它们。 – NaserShaikh