代码实现(封装后)
/**
* 缓存到SDCard
* 封装两个方法,
* 1:put
* 2:get
*/
public class LocalCache {
public void putImage(String imageUrl, Bitmap bitmap) throws Exception {
String newImage = MD5Unit.encode(imageUrl);
Log.e("newImage", newImage);
File file = new File(Environment.getExternalStorageDirectory() + "/BCache/" + newImage);
Log.e("看看目录结构", file.getAbsolutePath());
File parentFile = file.getParentFile();
Log.e("看看文件的父目录", parentFile.getAbsolutePath());
if (!parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
//Bitmap可以直接跟IO流就行直接交互
//compress 有三个参数,参数1:图片格式 参数2:对原图片进行压缩,参数3:流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e("-----", "图片写入成功 66哒");
fos.flush();
fos.close();
}
public Bitmap getImage(String imageUrl) throws Exception {
String newImage = MD5Unit.encode(imageUrl);
File file = new File(Environment.getExternalStorageDirectory() + "/BCache/" + newImage);
InputStream in = new FileInputStream(file);
Log.e("获取图片", "成功么么哒");
return BitmapFactory.decodeStream(in);
}
}
网友评论