L
istView中的图片优化(异步加载,SD卡缓存图片)
1、图片异步加载 |
2、SD卡缓存图片 |
代码: // 书的图片-图片的异步加载
final ImageView ivBbook = (ImageView) convertView.findViewById(R.id.book_img);
String filePath = book.getBookurl();
// 获得文件名
final String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
// 判断是否在sd卡有该图片
String storageState = Environment.getExternalStorageState();
File file = null;
if (Environment.MEDIA_MOUNTED.equals(storageState)) {
file = new File(Environment.getExternalStorageDirectory(),fileName);
}
if (file != null && file.exists()) {// /图片在sd卡有保存
ivBbook.setImageURI(Uri.fromFile(file));
Log.i(TAG, "从sd卡获取图片:" + fileName);
} else {// 图片文件不在sk卡保存
new LoadImageAsynTask<String, Void, Bitmap>(new LoadImageAsynTaskCallback<Bitmap>() {
@Override
public void beforeLoadImage() {
ivBbook.setImageResource(R.drawable.ic_launcher);
}
@Override
public void afterLoadImage(Bitmap bitmap) {
if (bitmap!=null) {
Log.i(TAG, "从服务器上下载图片"+fileName);
ivBbook.setImageBitmap(bitmap);
//保存bitmap到sd卡上
try {
//判断sd卡状态
String storageState = Environment.getExternalStorageState();
File file = null;
if (Environment.MEDIA_MOUNTED.equals(storageState)) {
file = new File(Environment.getExternalStorageDirectory(),fileName);
}else {
return;
}
CompressFormat format = CompressFormat.JPEG;
int quality = 100;//100无损保存
OutputStream stream = new FileOutputStream(file);
boolean b = bitmap.compress(format , quality , stream );
Log.i(TAG, "保存图片"+fileName+"到sd卡:"+b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else {
ivBbook.setImageResource(R.drawable.ic_launcher);
}
}
}){
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}.execute(filePath);
}
|