Android bitmap(五)完整例子ImageLoader

参考《android开发艺术探索》

1.图片压缩功能类ImageResizer

<pre>
public class ImageResizer{
private static final String TAG = "ImageResizer";

public ImageResizer(){
}

public Bitmap decodeSampledBitmapFromResource(Resource res,int resId,int reqWidth,int reqHeight){
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res,resId,options);
//calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
//decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res,resId,options);
}

public Bitmap decodeSampledBitmapFromFileDescriptor(FileDescriptor fd,int reqWidth, int reqHeight){
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd,null,options);
//calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
//decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fd,null,options);
}

public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
if(reqWidth == 0 || reqHeight == 0){
return 1;
}
//Raw height and width of image
final int width = options.outWidth;
final int height = options.outHeight;
Log.d(TAG,"origin,w="+width+"h="+height);
int inSampleSize = 1;

  if(height > reqHeight || width > reqWidth){
     final int halfHeight = height / 2;
     final int halfWidth = width / 2;
     while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){
        inSampleSize *= 2;
     }
  }
  Log.d(TAG,"sampleSize:"+inSampleSize);
  return inSampleSize;

}
}
</pre>

2.ImageLoader完整代码

<pre>
public class ImageLoader{
private static final String TAG = "ImageLoader";
public static final int MESSAGE_POST_RESULT = 1;

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final long KEEP_ALIVE = 10L;

private static final int TAG_KEY_URI = R.id.imageloader_uri;
private static final long DISK_CACHE_SIZE = 1024 * 1024 * 50;
private static final int IO_BUFFER_SIZE = 8 * 1024;
private static final int DISK_CACHE_INDEX = 0;
private boolean mIsDiskLruCacheCreated = false;

private static final ThreadFactory sThreadFactory = new ThreadFactory(){
private final AtomicInteger mCount = new AtomicInteger(1);

  public Thread newThread(Runnable r){
     return new Thread(r, "ImageLoader#" + mCount.getAndIncrement());
  }

}

public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
CORE_POOL_SIZE,MAXIMUM_POOL_SIZE,KEEP_ALIVE,TimeUnit.SECONDS,
new LinkedBlockingQueue<>(Runnable),sThreadFactory);

private Handler mMainHandler = new Handler(Looper.getMainLooper()){
public void handleMessage(Message msg){
LoaderResult result = (LoaderResult) msg.obj;
ImageView imageView = result.imageView;
String uri= (String) imageView.getTag(TAG_KEY_URI);
if(uri.equals(result.uri)){
imageView.setImageBitmap(result.bitmap);
}else{
Log.w(TAG,"set image bitmap,but url has changed,ignored!");
}
}
};

private Context mContext;
private ImageResizer mImageResizer = new ImageResizer();
private LruCache<String,Bitmap> mMemoryCache;
private DiskLruCache mDiskLruCache;

private ImageLoader(Context context){
mContext = context.getApplicationContext();
int maxMemory = (int) (Runtime.getRuntime().maxMemory / 1024);
int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
protected int sizeOf(String key,Bitmap bitmap){
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
};
File diskCacheDir = getDiskCacheDir(mContext, "bitmap");
if(!diskCacheDir.exists()){
diskCacheDir.mkdirs();
}
if(getUsableSpace(diskCacheDir) > DISK_CACHE_SIZE){
try{
mDiskLruCache = DiskLruCache.open(diskCacheDir,1,1,DISK_CACHE_SIZE);
mIsDiskLruCacheCreated = true;
}catch(IOException e){
e.printStackTrace();
}
}
}

public static ImageLoader build(Context context){
return new ImageLoader(context);
}

private void addBitmapToMemoryCache(String key,Bitmap bitmap){
if(getBitmapFromMemCache(key) == null){
mMemoryCache.put(key, bitmap);
}
}

private Bitmap getBitmapFromMemCache(String key){
return mMemoryCache.get(key);
}

public void bindBitmap(final String uri, final ImageView imageView){
bindBitmap(uri,imageView,0,0);
}

/**
* load bitmap from memory cache or disk or network async,then bind imageview and bitmap
* NOTE THAT: should run in UI thread
*/
public void bindBitmap(final String uri, final ImageView imageView, final int reqWidth,final int reqHeight){
imageView.setTag(TAG_KEY_URI,uri);
Bitmap bitmap = loadBitmapFromMemCache(uri);
if(bitmap != null){
imageView.setImageBitmap(bitmap);
return;
}

  Runnable loadBitmapTask = new Runnable(){
     public void run(){
       Bitmap bitmap = loadBitmap(uri, reqWidth, reqHeight);
       if(bitmap != null){
          LoaderResult result = new LoaderResult(imageView,uri,bitmap);
          mMainHandler.obtainMessage(MESSAGE_POST_RESULT,result).sendToTarget();
       }
     }
  }
  THREAD_POOL_EXECUTOR.execute(loadBitmapTask);

}

public Bitmap loadBitmap(String uri,int reqWidth,int reqHeight){
Bitmap bitmap = loadBitmapFromMemCache(uri);
if(bitmap != null){
Log.d(TAG,"loadBitmapFromMemCache,url:"+uri);
return bitmap;
}

  try{
     bitmap = loadBitmapFromDiskCache(uri,reqWidth,reqHeight);
     if(bitmap != null){
        Log.d(TAG,"loadBitmapFromDiskCache,url:"+uri);
        return bitmap;
     }
     bitmap = loadBitmapFromHttp(uri,reqWidth,reqHeight);
     Log.d(TAG,"loadBitmapFromHttp,url:"+uri);
  }catch(IOException e){
     e.printStackTrace();
  }
  
  if(bitmap == null && !mIsDiskLruCacheCreated){
     Log.w(TAG, "encounter error,DiskLruCache is not created.");
     bitmap = downloadBitmapFromUrl(uri);
  }
  return bitmap;

}

private Bitmap loadBitmapFromMemCache(String url){
final String key = hashKeyFromUrl(url);
Bitmap bitmap = getBitmapFromMemCache(key);
return bitmap;
}

private Bitmap loadBitmapFromHttp(String url,int reqWidth, int reqHeight) throws IOException{
if(Looper.myLooper() == Looper.getMainLooper()){
throw new RuntimeException("can not visit network from UI Thread.");
}
if(mDiskLruCache == null){
return null;
}
String key = hashKeyFromUrl(url);
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if(editor != null){
OutputStream outputStream = editor.newOutputStream(DISK_CACHE_INDEX);
if(downloadUrlToStream(url,outputStream)){
editor.commit();
}else{
editor.abort();
}
mDiskLruCache.flush();
}
return loadBitmapFromDiskCache(url,reqWidth,reqHeight);
}

private Bitmap loadBitmapFromDiskCache(String url,int reqWidth,int reqHeight){
if(Looper.myLooper() == Looper.getMainLooper()){
Log.w(TAG,"load bitmap from UI Thread,it is not recommended!");
}
if(mDiskLruCache == null){
return null;
}

  Bitmap bitmap = null;
  String key = hashKeyFromUrl(url);
  DiskLruCache.SnapShot snapShot = mDiskLruCache.get(key);
  if(snapShot != null){
     FileInputStream fileInputStream = (FileInputStream)snapShot.getInputStream(DISK_CACHE_INDEX);
     FileDescriptor fileDescriptor = fileInputStream.getFD();
     bitmap = mImageResizer.decodeSampledBitmapFromFileDescriptor(fileDescriptor,reqWidth,reqHeight);
     if(bitmap != null){
        addBitmapToMemoryCache(key,bitmap);
     }
  }
  return bitmap;

}

public boolean downloadUrlToStream(String urlString,OutputStream outputStream){
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try{
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(),IO_BUFFER_SIZE);
out = new BufferedOutputStream(outputStream,IO_BUFFER_SIZE);
int b;
while((b = in.read()) != -1){
out.write(b);
}
return true;
}catch(IOException e){
Log.e(TAG,"downloadBitmap failed."+e);
}finally{
if(urlConnection != null){
urlConnection.disconnect();
}
MyUtils.close(out);
MyUtils.close(in);
}
return false;
}

private Bitmap downloadBitmapFromUrl(String urlString){
Bitmap bitmap = null;
HttpURLConnection urlConnection = null;
BufferedInputStream in = null;
try{
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(),IO_BUFFER_SIZE);
bitmap = BitmapFactory.decodeStream(in);
}catch(IOException e){
Log.e(TAG,"Error in downloadBitmap:"+e);
}finally{
if(urlConnection != null){
urlConnection.disconnect();
}
MyUtils.close(in);
}
return bitmap;
}

private String hashKeyFromUrl(String url){
String cacheKey;
try{
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(url.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
}catch(NoSuchAlgorithmException e){
cacheKey = String.valueOf(url.hasCode());
}
return cacheKey;
}

private String bytesToHexString(byte[] bytes){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bytes.length; i ++){
String hex = Integer.toHexString(0xFF & byte[i]);
if(hex.length() == 1){
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}

public File getDiskCacheDir(Context context,String uniqueName){
boolean externalStorageAvailable = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
final String cachePath;
if(externalStorageAvailable){
cachePath = context.getExternalCacheDir().getPath();
}else{
cachePath = context.getCacheDir().getPath();
}
return new File(cachePath + File.separator + uniqueName);
}

private long getUsableSpace(File path){
if(Build.VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD){
return path.getUsableSpace();
}
final StatFs stats = new StatFs(path.getPath());
return (long) stats.getBloackSize() * (long)stats.getAvailableBlocks();
}

private static class LoaderResult{
public ImageView imageView;
public String uri;
public Bitmap bitmap;

  public LoaderResult(ImageView imageView,String uri,Bitmap bitmap){
     this.imageView = imageView;
     this.uri = uri;
     this.bitmap = bitmap;
  }

}
}
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,285评论 25 707
  • 英语里面有一句“less is more”,我译成少比多好。现在我觉得少即是多更好。源于今晚看到一张图片顺便分享给...
    A00Helen阅读 161评论 0 0
  • 23种创新模式总署父文链接 享元模式的主要目的是实现对象的共享,即共享池,当系统中对象多的时候可以减少内存的开销 ...
    风___________阅读 248评论 0 0
  • 从没深入考虑过类似的问题。而近期来,有了孩子,家里年事已高的老人也陆续步入了需要照顾的阶段。突然疑惑了,太多人在对...
    珂望_阅读 434评论 0 0