ImageLoader图片加载

介绍

学习了《Android开发艺术探索》后,准备自己练习一下线程池、LruCache、DiskLruCache、图片压缩,就自己写了ImageLoader并在观看数的基础上就行了优化,防止了空指针异常,但是若在线程池中加载多个相同链接的图片会出现Bug,尝试了一种方法,但自己功力不够,于是就放弃了。

两个问题

  1. 空指针异常:在ImageLoader的构造函数中会创建LruCache、DiskLruCache对象并初始化(UI线程),执行asyncLoadImage时(子线程),构造函数可能未执行完全,造成缓存对象空指针异常
  2. 相同链接的图片会:相同链接具有相同的key,在第一子线程执行后可能创建editor对象(未完全存入bitmap,即空文件),第二子线程会判端当前DIsk缓存不为空(找到空文件),转换成bitmap对象并放入imageview中,则第二个imageview的图片为空

使用方法

1
2
3
4
5
6
7
loader = new ImageLoader(this);
photo = (ImageView) findViewById(R.id.photo);
photo1 = (ImageView) findViewById(R.id.photo1);
loader.asyncLoadImage("http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg"
,photo,200,100);
loader.asyncLoadImage("http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg"
,photo1,200,100);

源码

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
public class ImageLoader {
private Context mContext;
private static final int CPU_Count = Runtime.getRuntime().availableProcessors();
private static final int Core_Size = CPU_Count+1;
private static final int Pool_Size = 2 * CPU_Count +1;
private static final int Disk_Cache_Szie = 20*1024*1024;
private static final Executor Image_Load_Pool = new ThreadPoolExecutor(Core_Size,Pool_Size
,5, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
private LruCache<String,Bitmap> memoryCache;
private DiskLruCache diskCache;
private Handler mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
ImageResult result = (ImageResult) msg.obj;
Bitmap bitmap = result.bitmap;
ImageView imageView = result.iv;
String key = result.key;
if (key.equals(imageView.getTag())){
imageView.setImageBitmap(bitmap);
}else{
Log.d("MMP:","there is a question that i can not resolve.");
}
}
};
public ImageLoader(Context context){
mContext = context.getApplicationContext();
{
int memorySize = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSzie = memorySize / 10;
memoryCache = new LruCache<String, Bitmap>(cacheSzie) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
};
}
{
File cacheDir = getDiskCacheDir(mContext,"image");
if (!cacheDir.exists())
cacheDir.mkdir();
if (cacheDir.getFreeSpace()>Disk_Cache_Szie){
try {
diskCache = DiskLruCache.open(cacheDir,1,1,Disk_Cache_Szie);
} catch (IOException e) {
e.printStackTrace();
}
}
synchronized (this){
notifyAll();
}
}
private File getDiskCacheDir(Context context, String uniqueName) {
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
cachePath = context.getExternalCacheDir().getPath();
} else {
cachePath = context.getCacheDir().getPath();
}
return new File(cachePath + File.separator + uniqueName);
}
private Bitmap decodeBitmapFromResource(Resources resources,int id,int reqWidth,int reqHeight){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources,id,options);
options.inSampleSize = caculateInSample(options,reqWidth,reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(resources,id,options);
}
private Bitmap decodeBitmapFromFileDescriptor(FileDescriptor fd, int reqWidth, int reqHeight){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd,null,options);
options.inSampleSize = caculateInSample(options,reqWidth,reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fd,null,options);
}
private int caculateInSample(BitmapFactory.Options options,int reqWidth,int reqHeight){
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (width>reqWidth||height>reqHeight){
while (width/(2*inSampleSize) >=reqWidth&&height/(2*inSampleSize)>=reqHeight)
inSampleSize *=2;
}
return inSampleSize;
}
/*
*网络请求下载Bitmap
*需在子线程中使用加载Bitmap
*/
private boolean downloadToStream(String imageurl, OutputStream os){
HttpURLConnection connection = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(imageurl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3500);
connection.setReadTimeout(3500);
bis = new BufferedInputStream(connection.getInputStream(),1024*1024);
bos = new BufferedOutputStream(os,1024*1024);
int b;
while ((b = bis.read())!=-1){
bos.write(b);
}
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (connection!=null){
connection.disconnect();
try {
if (bis!=null)
bis.close();
if (bos!=null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/*
*Http下载Bitmap并存入硬Disk缓存
*需在子线程中使用加载Bitmap
*/
private Bitmap loadImageFromHttp(String url,int reqWidth,int reqHeight){
if (Looper.myLooper()==Looper.getMainLooper()){
throw new RuntimeException("Can not download image by main thread");
}
// If the thread has been started, wait until the diskcache has been created.
synchronized (this) {
if (diskCache == null) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
String key = ""+url.hashCode();
try {
DiskLruCache.Editor editor = diskCache.edit(key);
if (editor!=null){
OutputStream os =editor.newOutputStream(0);
if (downloadToStream(url,os)){
editor.commit();
}else{
editor.abort();
}
}
diskCache.flush();
} catch (IOException e) {
e.printStackTrace();
}
return loadImageFromDisk(url,reqWidth,reqHeight);
}
/*
*Disk缓存加载Bitmap并放入内存缓存
*需在子线程中使用加载Bitmap
*/
private Bitmap loadImageFromDisk(String url,int reqWidth,int reqHeight){
if (Looper.myLooper()==Looper.getMainLooper()){
throw new RuntimeException("Can not load disk image by main thread");
}
// If the thread has been started, wait until the diskcache has been created.
synchronized (this) {
if (diskCache == null) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
String key = ""+url.hashCode();
Bitmap bitmap = null;
try {
DiskLruCache.Snapshot snapshot = diskCache.get(key);
if (snapshot!=null) {
FileInputStream fis = (FileInputStream) snapshot.getInputStream(0);
FileDescriptor descriptor = fis.getFD();
bitmap = decodeBitmapFromFileDescriptor(descriptor,reqWidth,reqHeight);
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bitmap!=null){
addBitmapToMemory(key,bitmap);
}
}
return bitmap;
}
/*
*二级缓存加载Bitmap
*需在子线程中使用加载Bitmap
*/
public Bitmap loadBitmap(String url,int reqWidth,int reqHeight){
String key = ""+url.hashCode();
Bitmap bitmap = getBitmapFromMemory(key);
if (bitmap!=null)
return bitmap;
bitmap = loadImageFromDisk(url,reqWidth,reqHeight);
if (bitmap!=null)
return bitmap;
bitmap = loadImageFromHttp(url,reqWidth,reqHeight);
return bitmap;
}
/*
*加载图片
*线程池中加载Bitmap
*/
public void asyncLoadImage(final String url,final ImageView imageView, final int reqWidth, final int reqHeight){
final String key = ""+url.hashCode();
Bitmap bitmap = getBitmapFromMemory(key);
imageView.setTag(key);
if (bitmap!=null){
imageView.setImageBitmap(bitmap);
return ;
}
Runnable load_image = new Runnable() {
@Override
public void run() {
Bitmap bitmap = loadBitmap(url,reqWidth,reqHeight);
ImageResult result = new ImageResult(imageView,bitmap,key);
Message message = mHandler.obtainMessage(0,result);
mHandler.sendMessage(message);
}
};
Image_Load_Pool.execute(load_image);
}
private void addBitmapToMemory(String key,Bitmap bitmap){
if (memoryCache== null) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (getBitmapFromMemory(key)==null){
memoryCache.put(key,bitmap);
}
}
private Bitmap getBitmapFromMemory(String key){
if (memoryCache== null) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return memoryCache.get(key);
}
private static class ImageResult{
public ImageView iv;
public String key;
public Bitmap bitmap;
public ImageResult(ImageView iv, Bitmap bitmap, String key) {
this.iv = iv;
this.key = key;
this.bitmap = bitmap;
}
}
}