Android图像处理学习
##大图片处理
Android系统为每一个应用所分配的内存都是固定有限的,一般由手机厂商设置,最小为16M。图片有不同的形状与大小。在大多数情况下它们的实际大小都比需要呈现的尺寸大很多,所以我们只需要在内存中加载一个低分辨率的照片即可。为了更便于显示,这个低分辨率的照片应该是与其对应的UI控件大小相匹配的。
读取位图的尺寸和类型1
2
3
4
5options.inJustDecodeBounds = true; //true表示在解码的时候避免内存的分配,它会返回一个null的Bitmap,但是可以获取到 outWidth, outHeight 与 outMimeType。
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);//解码的方法,根据数据源不同,有decodeByteArray(), decodeFile(), decodeResource()等几种
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
加载一个按比例缩小的版本到内存中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//计算需要缩放的比例的函数
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
//加载位图
public static Bitmap decodeSampledBitmapFromResource(Resources 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);
}
当图片来源是网络或者是存储卡时(或者是任何不在内存中的形式),这些方法都不应该在UI 线程中执行。
可以使用AsyncTask来处理,不过当使用listView或gridView加载图片时,很容易引起并发问题(多个线程争抢同一个资源),
当要加载多张大图片时,一般使用内存缓存与磁盘缓存来提高响应速度与UI流畅度。
##使用内存缓存
##使用磁盘缓存