package com.zhy.utils; import java.io.File; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v4.util.LruCache; import android.util.Log; import android.widget.ImageView; import com.zhy.utils.ImageSizeUtil.ImageSize; /** * 图片加载类 * http://blog.csdn.net/lmj623565791/article/details/41874561 * @author zhy * */ public class ImageLoader { private static ImageLoader mInstance; /** * 图片缓存的核心对象 */ private LruCache<String, Bitmap> mLruCache; /** * 线程池 */ private ExecutorService mThreadPool; private static final int DEAFULT_THREAD_COUNT = 1; //默认线程数 1 个 /** * 队列的调度方式 */ private Type mType = Type.LIFO; /** * 任务队列 */ private LinkedList<Runnable> mTaskQueue; /** * 后台轮询线程 */ private Thread mPoolThread; private Handler mPoolThreadHandler; /** * UI线程中的Handler */ private Handler mUIHandler; /** * mSemaphorePoolThreadHandler = new Semaphore(0); * 用于控制我们的mPoolThreadHandler的初始化完成,我们在使用 * mPoolThreadHandler会进行判空,如果为null,会通过mSemaphorePoolThreadHandler.acquire()进行阻塞; * 当mPoolThreadHandler初始化结束,我们会调用.release();解除阻塞。 */ private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0); private Semaphore mSemaphoreThreadPool; private boolean isDiskCacheEnable = true; //是否进行本地硬盘缓存 private static final String TAG = "ImageLoader"; public enum Type { FIFO, LIFO; // LAST IN FAST OUT } private ImageLoader(int threadCount, Type type) { init(threadCount, type); } /** * 初始化 * * @param threadCount * @param type */ private void init(int threadCount, Type type) { initBackThread(); // 获取我们应用的最大可用内存 int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cacheMemory = maxMemory / 8; // 内存缓存的最大容量为: 程序最大容量的八分之一 mLruCache = new LruCache<String, Bitmap>(cacheMemory) { @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); // 图片的大小 } }; // 创建线程池 mThreadPool = Executors.newFixedThreadPool(threadCount); // 数量确定的线程池 mTaskQueue = new LinkedList<Runnable>(); mType = type; mSemaphoreThreadPool = new Semaphore(threadCount); // 信号量的个数(threadCount) } /** * 初始化后台轮询线程 */ private void initBackThread() { // 后台轮询线程 mPoolThread = new Thread() { @Override public void run() { Looper.prepare(); mPoolThreadHandler = new Handler() //子线程中的轮询handler { @Override public void handleMessage(Message msg) { // 线程池去取出一个任务进行执行 mThreadPool.execute(getTask()); try { mSemaphoreThreadPool.acquire(); } catch (InterruptedException e) { } } }; // 释放一个信号量 mSemaphorePoolThreadHandler.release(); Looper.loop(); // }; }; mPoolThread.start(); } public static ImageLoader getInstance() { if (mInstance == null) { synchronized (ImageLoader.class) { if (mInstance == null) { mInstance = new ImageLoader(DEAFULT_THREAD_COUNT, Type.LIFO); } } } return mInstance; } public static ImageLoader getInstance(int threadCount, Type type) { if (mInstance == null) { synchronized (ImageLoader.class) { if (mInstance == null) { mInstance = new ImageLoader(threadCount, type); } } } return mInstance; } /** * 根据path为imageview设置图片 * * @param path * @param imageView */ public void loadImage(final String path, final ImageView imageView, final boolean isFromNet) { imageView.setTag(path); if (mUIHandler == null) { mUIHandler = new Handler() { public void handleMessage(Message msg) { // 获取得到图片,为imageview回调设置图片 ImgBeanHolder holder = (ImgBeanHolder) msg.obj; Bitmap bm = holder.bitmap; ImageView imageview = holder.imageView; String path = holder.path; // 将path与getTag存储路径进行比较 if (imageview.getTag().toString().equals(path)) { imageview.setImageBitmap(bm); } }; }; } // 根据path在缓存中获取bitmap Bitmap bm = getBitmapFromLruCache(path); if (bm != null) { refreashBitmap(path, imageView, bm); } else { addTask(buildTask(path, imageView, isFromNet)); } } /** * 根据传入的参数,新建一个任务 * * @param path * @param imageView * @param isFromNet * @return */ private Runnable buildTask(final String path, final ImageView imageView, final boolean isFromNet) { return new Runnable() { @Override public void run() { Bitmap bm = null; if (isFromNet) { File file = getDiskCacheDir(imageView.getContext(), md5(path)); if (file.exists())// 如果在缓存文件中发现 { Log.e(TAG, "find image :" + path + " in disk cache ."); bm = loadImageFromLocal(file.getAbsolutePath(), imageView); } else { if (isDiskCacheEnable)// 检测是否开启硬盘缓存 { boolean downloadState = DownloadImgUtils .downloadImgByUrl(path, file); if (downloadState)// 如果下载成功 ,就从本地进行下载 { Log.e(TAG, "download image :" + path + " to disk cache . path is " + file.getAbsolutePath()); bm = loadImageFromLocal(file.getAbsolutePath(), imageView); } } else // 直接从网络加载 { Log.e(TAG, "load image :" + path + " to memory."); bm = DownloadImgUtils.downloadImgByUrl(path, imageView); } } } else { bm = loadImageFromLocal(path, imageView); } // 3、把图片加入到缓存 addBitmapToLruCache(path, bm); refreashBitmap(path, imageView, bm); mSemaphoreThreadPool.release(); } }; } private Bitmap loadImageFromLocal(final String path, final ImageView imageView) { Bitmap bm; // 加载图片 // 图片的压缩 // 1、获得图片需要显示的大小 ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView); // 2、压缩图片 bm = decodeSampledBitmapFromPath(path, imageSize.width, imageSize.height); return bm; } /** * 从任务队列取出一个方法 * * @return */ private Runnable getTask() { if (mType == Type.FIFO) { return mTaskQueue.removeFirst(); } else if (mType == Type.LIFO) { return mTaskQueue.removeLast(); } return null; } /** * 利用签名辅助类,将字符串字节数组 * * @param str * @return */ public String md5(String str) { byte[] digest = null; try { MessageDigest md = MessageDigest.getInstance("md5"); digest = md.digest(str.getBytes()); return bytes2hex02(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 方式二 * * @param bytes * @return */ public String bytes2hex02(byte[] bytes) { StringBuilder sb = new StringBuilder(); String tmp = null; for (byte b : bytes) { // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制 tmp = Integer.toHexString(0xFF & b); if (tmp.length() == 1)// 每个字节8为,转为16进制标志,2个16进制位 { tmp = "0" + tmp; } sb.append(tmp); } return sb.toString(); } private void refreashBitmap(final String path, final ImageView imageView, Bitmap bm) { Message message = Message.obtain(); ImgBeanHolder holder = new ImgBeanHolder(); holder.bitmap = bm; holder.path = path; holder.imageView = imageView; message.obj = holder; mUIHandler.sendMessage(message); } /** * 将图片加入LruCache * * @param path * @param bm */ protected void addBitmapToLruCache(String path, Bitmap bm) { if (getBitmapFromLruCache(path) == null) { if (bm != null) mLruCache.put(path, bm); } } /** * 根据图片需要显示的宽和高对图片进行压缩 * * @param path * @param width * @param height * @return */ protected Bitmap decodeSampledBitmapFromPath(String path, int width, int height) { // 获得图片的宽和高,并不把图片加载到内存中 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options, width, height); // 使用获得到的InSampleSize再次解析图片 options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(path, options); return bitmap; } private synchronized void addTask(Runnable runnable) { mTaskQueue.add(runnable); // if(mPoolThreadHandler==null)wait(); try { if (mPoolThreadHandler == null) mSemaphorePoolThreadHandler.acquire(); // 他的作用是什么呢??? 看灰机 } catch (Exception e) { } mPoolThreadHandler.sendEmptyMessage(0x110); } /** * 获得缓存图片的地址 * * @param context * @param uniqueName 使用md5 作为其文件名 * @return */ public File getDiskCacheDir(Context context, String uniqueName) { String cachePath; if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { cachePath = context.getExternalCacheDir().getPath(); } else { cachePath = context.getCacheDir().getPath(); } return new File(cachePath + File.separator + uniqueName); } /** * 根据path在缓存中获取bitmap * * @param key * @return */ private Bitmap getBitmapFromLruCache(String key) { return mLruCache.get(key); } private class ImgBeanHolder { Bitmap bitmap; ImageView imageView; String path; } }
其他的一些类
package com.zhy.utils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.util.Log; import android.widget.ImageView; import com.zhy.utils.ImageSizeUtil.ImageSize; /** * http://blog.csdn.net/lmj623565791/article/details/41874561 * @author zhy * */ public class DownloadImgUtils { /** * 根据url下载图片在指定的文件 * * @param urlStr * @param file * @return */ public static boolean downloadImgByUrl(String urlStr, File file) { FileOutputStream fos = null; InputStream is = null; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); is = conn.getInputStream(); fos = new FileOutputStream(file); byte[] buf = new byte[512]; int len = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); return true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } return false; } /** * 根据url下载图片在指定的文件 * * @param urlStr * @param file * @return */ public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview) { FileOutputStream fos = null; InputStream is = null; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(conn.getInputStream()); is.mark(is.available()); // 最为一个标记来表示位置 Options opts = new Options(); opts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts); //获取imageview想要显示的宽和高 ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview); opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts, imageViewSize.width, imageViewSize.height); opts.inJustDecodeBounds = false; is.reset(); // 重新设置其其实位置, 达到该流能够重复使用的效果 bitmap = BitmapFactory.decodeStream(is, null, opts); conn.disconnect(); return bitmap; } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } return null; } }
package com.zhy.utils; public class Images { public final static String[] imageThumbUrls = new String[] { "http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383166_3407.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383165_7197.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383150_8410.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383131_3736.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383130_5094.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383130_7393.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383129_8813.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383100_3554.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383093_7894.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383092_2432.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383092_3071.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383091_3119.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383059_6589.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383059_8814.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383059_2237.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383058_4330.jpg", "http://img.my.csdn.net/uploads/201407/26/1406383038_3602.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382942_3079.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382942_8125.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382942_4881.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382941_4559.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382941_3845.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382924_8955.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382923_2141.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382923_8437.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382922_6166.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382922_4843.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382905_5804.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382904_3362.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382904_2312.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382904_4960.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382900_2418.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382881_4490.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382881_5935.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382880_3865.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382880_4662.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382879_2553.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382862_5375.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382862_1748.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382861_7618.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382861_8606.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382861_8949.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382841_9821.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382840_6603.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382840_2405.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382840_6354.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382839_5779.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382810_7578.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382810_2436.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382809_3883.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382809_6269.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382808_4179.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382790_8326.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382789_7174.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382789_5170.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382789_4118.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382788_9532.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382767_3184.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382767_4772.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382766_4924.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382766_5762.jpg", "http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg" }; }
package com.zhy.utils; import java.lang.reflect.Field; import android.annotation.TargetApi; import android.graphics.BitmapFactory.Options; import android.os.Build; import android.util.DisplayMetrics; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; /** * http://blog.csdn.net/lmj623565791/article/details/41874561 * @author zhy * */ public class ImageSizeUtil { /** * 根据需求的宽和高以及图片实际的宽和高计算SampleSize * * @param options * @param width * @param height * @return */ public static int caculateInSampleSize(Options options, int reqWidth, int reqHeight) { int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (width > reqWidth || height > reqHeight) { int widthRadio = Math.round(width * 1.0f / reqWidth); int heightRadio = Math.round(height * 1.0f / reqHeight); inSampleSize = Math.max(widthRadio, heightRadio); } return inSampleSize; } /** * 根据ImageView获适当的压缩的宽和高 * * @param imageView * @return */ public static ImageSize getImageViewSize(ImageView imageView) { ImageSize imageSize = new ImageSize(); DisplayMetrics displayMetrics = imageView.getContext().getResources() .getDisplayMetrics(); LayoutParams lp = imageView.getLayoutParams(); int width = imageView.getWidth();// 获取imageview的实际宽度 if (width <= 0) { width = lp.width;// 获取imageview在layout中声明的宽度 } if (width <= 0) { //width = imageView.getMaxWidth();// 检查最大值 width = getImageViewFieldValue(imageView, "mMaxWidth"); /* * 可以看到这里或者最大宽度,我们用的反射,而不是getMaxWidth();维萨呢, * 因为getMaxWidth竟然要API 16,我也是醉了;为了兼容性,我们采用反射的方 * 案。 * */ } if (width <= 0) { width = displayMetrics.widthPixels; } int height = imageView.getHeight();// 获取imageview的实际高度 if (height <= 0) { height = lp.height;// 获取imageview在layout中声明的宽度 } if (height <= 0) { height = getImageViewFieldValue(imageView, "mMaxHeight");// 检查最大值 } if (height <= 0) { height = displayMetrics.heightPixels; } imageSize.width = width; imageSize.height = height; return imageSize; } public static class ImageSize { int width; int height; } /** * 通过反射获取imageview的某个属性值 * * @param object * @param fieldName * @return */ private static int getImageViewFieldValue(Object object, String fieldName) { int value = 0; try { Field field = ImageView.class.getDeclaredField(fieldName); field.setAccessible(true); int fieldValue = field.getInt(object); if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) { value = fieldValue; } } catch (Exception e) { } return value; } }