双击代码复制

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

importjava.lang.reflect.Field;

importjava.util.LinkedList;

importjava.util.concurrent.ExecutorService;

importjava.util.concurrent.Executors;

importjava.util.concurrent.Semaphore;

 

importandroid.graphics.Bitmap;

importandroid.graphics.BitmapFactory;

importandroid.os.Handler;

importandroid.os.Looper;

importandroid.os.Message;

importandroid.support.v4.util.LruCache;

importandroid.util.DisplayMetrics;

importandroid.view.ViewGroup.LayoutParams;

importandroid.widget.ImageView;

 

publicclass ImageLoader {

    /**

     * 图片缓存的核心类

     */

    privateLruCache mLruCache;

    /**

     * 线程池

     */

    privateExecutorService mThreadPool;

    /**

     * 队列的调度方式

     */

    privateType mType = Type.LIFO;

    /**

     * 任务队列

     */

    privateLinkedList mTasks;

    /**

     * 轮询的线程

     */

    privateThread mPoolThread;

    privateHandler mPoolThreadHander;

 

    /**

     * 运行在UI线程的handler,用于给ImageView设置图片

     */

    privateHandler mHandler;

 

    /**

     * 引入一个值为1的信号量,防止mPoolThreadHander未初始化完成

     */

    privatevolatile Semaphore mSemaphore = newSemaphore(0);

 

    /**

     * 引入一个值为1的信号量,由于线程池内部也有一个阻塞线程,防止加入任务的速度过快,使LIFO效果不明显

     */

    privatevolatile Semaphore mPoolSemaphore;

 

    privatestatic ImageLoader mInstance;

 

    /**

     * 队列的调度方式

     *

     * @author zhy

     *

     */

    publicenum Type {

        FIFO, LIFO

    }

 

    /**

     * 单例获得该实例对象

     *

     * @return

     */

    publicstatic ImageLoader getInstance() {

 

        if(mInstance == null) {

            synchronized(ImageLoader.class) {

                if(mInstance == null) {

                    mInstance = newImageLoader(1, Type.LIFO);

                }

            }

        }

        returnmInstance;

    }

 

    privateImageLoader(intthreadCount, Type type) {

        init(threadCount, type);

    }

 

    privatevoid init(intthreadCount, Type type) {

        // loop thread

        mPoolThread = newThread() {

            @Override

            publicvoid run() {

                Looper.prepare();

 

                mPoolThreadHander = newHandler() {

                    @Override

                    publicvoid handleMessage(Message msg) {

                        mThreadPool.execute(getTask());

                        try{

                            mPoolSemaphore.acquire();

                        }catch(InterruptedException e) {

                        }

                    }

                };

                // 释放一个信号量

                mSemaphore.release();

                Looper.loop();

            }

        };

        mPoolThread.start();

 

        // 获取应用程序最大可用内存

        intmaxMemory = (int) Runtime.getRuntime().maxMemory();

        intcacheSize = maxMemory / 8;

        mLruCache = newLruCache(cacheSize) {

            @Override

            protectedint sizeOf(String key, Bitmap value) {

                returnvalue.getRowBytes() * value.getHeight();

            };

        };

 

        mThreadPool = Executors.newFixedThreadPool(threadCount);

        mPoolSemaphore = newSemaphore(threadCount);

        mTasks = newLinkedList();

        mType = type == null? Type.LIFO : type;

 

    }

 

    /**

     * 加载图片

     *

     * @param path

     * @param imageView

     */

    publicvoid loadImage(finalString path, finalImageView imageView) {

        // set tag

        imageView.setTag(path);

        // UI线程

        if(mHandler == null) {

            mHandler = newHandler() {

                @Override

                publicvoid handleMessage(Message msg) {

                    ImgBeanHolder holder = (ImgBeanHolder) msg.obj;

                    ImageView imageView = holder.imageView;

                    Bitmap bm = holder.bitmap;

                    String path = holder.path;

                    if(imageView.getTag().toString().equals(path)) {

                        imageView.setImageBitmap(bm);

                    }

                }

            };

        }

 

        Bitmap bm = getBitmapFromLruCache(path);

        if(bm != null) {

            ImgBeanHolder holder = newImgBeanHolder();

            holder.bitmap = bm;

            holder.imageView = imageView;

            holder.path = path;

            Message message = Message.obtain();

            message.obj = holder;

            mHandler.sendMessage(message);

        }else{

            addTask(newRunnable() {

                @Override

                publicvoid run() {

 

                    ImageSize imageSize = getImageViewWidth(imageView);

 

                    intreqWidth = imageSize.width;

                    intreqHeight = imageSize.height;

 

                    Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth,

                            reqHeight);

                    addBitmapToLruCache(path, bm);

                    ImgBeanHolder holder = newImgBeanHolder();

                    holder.bitmap = getBitmapFromLruCache(path);

                    holder.imageView = imageView;

                    holder.path = path;

                    Message message = Message.obtain();

                    message.obj = holder;

                    // Log.e("TAG", "mHandler.sendMessage(message);");

                    mHandler.sendMessage(message);

                    mPoolSemaphore.release();

                }

            });

        }

 

    }

 

    /**

     * 添加一个任务

     *

     * @param runnable

     */

    privatesynchronized void addTask(Runnable runnable) {

        try{

            // 请求信号量,防止mPoolThreadHander为null

            if(mPoolThreadHander == null)

                mSemaphore.acquire();

        }catch(InterruptedException e) {

        }

        mTasks.add(runnable);

 

        mPoolThreadHander.sendEmptyMessage(0x110);

    }

 

    /**

     * 取出一个任务

     *

     * @return

     */

    privatesynchronized Runnable getTask() {

        if(mType == Type.FIFO) {

            returnmTasks.removeFirst();

        }elseif (mType == Type.LIFO) {

            returnmTasks.removeLast();

        }

        returnnull;

    }

 

    /**

     * 单例获得该实例对象

     *

     * @return

     */

    publicstatic ImageLoader getInstance(intthreadCount, Type type) {

 

        if(mInstance == null) {

            synchronized(ImageLoader.class) {

                if(mInstance == null) {

                    mInstance = newImageLoader(threadCount, type);

                }

            }

        }

        returnmInstance;

    }

 

    /**

     * 根据ImageView获得适当的压缩的宽和高

     *

     * @param imageView

     * @return

     */

    privateImageSize getImageViewWidth(ImageView imageView) {

        ImageSize imageSize = newImageSize();

        finalDisplayMetrics displayMetrics = imageView.getContext()

                .getResources().getDisplayMetrics();

        finalLayoutParams params = imageView.getLayoutParams();

 

        intwidth = params.width == LayoutParams.WRAP_CONTENT ? 0: imageView

                .getWidth();// Get actual image width

        if(width <= 0)

            width = params.width; // Get layout width parameter

        if(width <= 0)

            width = getImageViewFieldValue(imageView, "mMaxWidth");// Check

                                                                    // maxWidth

                                                                    // parameter

        if(width <= 0)

            width = displayMetrics.widthPixels;

        intheight = params.height == LayoutParams.WRAP_CONTENT ? 0: imageView

                .getHeight();// Get actual image height

        if(height <= 0)

            height = params.height; // Get layout height parameter

        if(height <= 0)

            height = getImageViewFieldValue(imageView, "mMaxHeight");// Check

                                                                        // maxHeight

                                                                        // parameter

        if(height <= 0)

            height = displayMetrics.heightPixels;

        imageSize.width = width;

        imageSize.height = height;

        returnimageSize;

 

    }

 

    /**

     * 从LruCache中获取一张图片,如果不存在就返回null。

     */

    privateBitmap getBitmapFromLruCache(String key) {

        returnmLruCache.get(key);

    }

 

    /**

     * 往LruCache中添加一张图片

     *

     * @param key

     * @param bitmap

     */

    privatevoid addBitmapToLruCache(String key, Bitmap bitmap) {

        if(getBitmapFromLruCache(key) == null) {

            if(bitmap != null)

                mLruCache.put(key, bitmap);

        }

    }

 

    /**

     * 计算inSampleSize,用于压缩图片

     *

     * @param options

     * @param reqWidth

     * @param reqHeight

     * @return

     */

    privateint calculateInSampleSize(BitmapFactory.Options options,

            intreqWidth, intreqHeight) {

        // 源图片的宽度

        intwidth = options.outWidth;

        intheight = options.outHeight;

        intinSampleSize = 1;

 

        if(width > reqWidth && height > reqHeight) {

            // 计算出实际宽度和目标宽度的比率

            intwidthRatio = Math.round((float) width / (float) reqWidth);

            intheightRatio = Math.round((float) width / (float) reqWidth);

            inSampleSize = Math.max(widthRatio, heightRatio);

        }

        returninSampleSize;

    }

 

    /**

     * 根据计算的inSampleSize,得到压缩后图片

     *

     * @param pathName

     * @param reqWidth

     * @param reqHeight

     * @return

     */

    privateBitmap decodeSampledBitmapFromResource(String pathName,

            intreqWidth, intreqHeight) {

        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小

        finalBitmapFactory.Options options = newBitmapFactory.Options();

        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(pathName, options);

        // 调用上面定义的方法计算inSampleSize值

        options.inSampleSize = calculateInSampleSize(options, reqWidth,

                reqHeight);

        // 使用获取到的inSampleSize值再次解析图片

        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);

 

        returnbitmap;

    }

 

    privateclass ImgBeanHolder {

        Bitmap bitmap;

        ImageView imageView;

        String path;

    }

 

    privateclass ImageSize {

        intwidth;

        intheight;

    }

 

    /**

     * 反射获得ImageView设置的最大宽度和高度

     *

     * @param object

     * @param fieldName

     * @return

     */

    privatestatic int getImageViewFieldValue(Object object, String fieldName) {

        intvalue = 0;

        try{

            Field field = ImageView.class.getDeclaredField(fieldName);

            field.setAccessible(true);

            intfieldValue = (Integer) field.get(object);

            if(fieldValue > 0&& fieldValue < Integer.MAX_VALUE) {

                value = fieldValue;

            }

        }catch(Exception e) {

        }

        returnvalue;

    }

 

}

使用很简单,如果你在是Adapter中,

双击代码复制

1

2

3

4

5

ImageItem item = getItem(position);

        String path = item.getPath();

        ImageView imageView = holder.getImageView(R.id.img_plant);

        ImageLoader.getInstance().loadImage(path, imageView);

        imageView.setImageResource(R.drawable.pictures_no);

 

更多相关文章

  1. Android获取图片Uri/path
  2. 【Android】图片切换组件ImageSwitcher的运用
  3. Android 创建圆形背景图片
  4. Android base64 上传图片
  5. Android显示网络图片相关实现方法浅谈
  6. android 中Drawable跟Bitmap转换及常用于图片相关操作方法 - And
  7. android带图片的AlertDialog和文件管理器(代码)
  8. android GridView实现选中图片放大。

随机推荐

  1. GitHub还真把所有代码埋到北极地下了,我特
  2. ssm实战购物商城系统
  3. MobX
  4. dva
  5. 嵌入式:我不是针对谁,我是说在座的Javaer都
  6. 戴耳机敲代码,我都听些啥?
  7. 外边距合并规则
  8. redux-saga
  9. 详解HDFS3.x新特性-纠删码
  10. 深入理解Java:内部类