I've covered how to generate thumbnail images from a Bitmap in Android, but I wanted to let you in on my helper class to cache Bitmaps onto the filesystem.
Here's the class.
Text Snippet:
package com.rogerethomas.helper;
import java.io.File;
import java.io.FileOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
public class BitmapCacheHelper extends AsyncTask<Integer, Void, String> {
private final File fileRef;
private final String cachePath;
private final String fileName;
public BitmapCacheHelper(File file, String pathToCache, String nameOfFile) {
fileRef = file;
cachePath = pathToCache;
fileName = nameOfFile;
}
@Override
protected String doInBackground(Integer... params) {
try {
Bitmap resized = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(fileRef.getPath()), params[1], params[0]);
File fileNew = new File(cachePath, fileName);
FileOutputStream fOutStream = new FileOutputStream(fileNew);
resized.compress(Bitmap.CompressFormat.JPEG, params[2], fOutStream);
fOutStream.flush();
fOutStream.close();
resized.recycle();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(String string) {
}
}
I generally use a private method to call this task. Here's what I'm using at the moment:
Text Snippet:
private void generateCached(File file, String cachePath, String fileName) {
try {
BitmapCacheHelper helper = new BitmapCacheHelper(file, cachePath, fileName);
helper.execute(200, 200, 60);
} catch (Exception e) {
}
}
The parameters in execute stand for: (width, height, quality)
That's about it! Caching Bitmaps in Android is an absolute breeze.
