Android图片缩放

图片缩放有3种办法:

1.BitmapFactory和BitmapFactory.Options。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 记得把assets目录下的图片拷贝到SD卡中
// 由于设置inJustDecodeBounds为true,因此执行下面代码后bitmap为空
mBitmap = BitmapFactory.decodeFile("/sdcard/image.jpg", options);
// 计算缩放比例,由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int scale = (int) (options.outHeight / (float) 200);
// 因为结果为int型,如果相除后值为0.n,则最终结果将是0
if (scale <= 0)
{
scale = 1;
}
System.out.println("Scale=" + scale);
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
// 重新读入图片,注意此时已经把options.inJustDecodeBounds设回false
mBitmap = BitmapFactory.decodeFile("/sdcard/image.jpg", options);
int width = mBitmap.getWidth();
int height = mBitmap.getHeight();
System.out.println(width + " " + height);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(mBitmap);

此方法缩放只能是等比例缩放
参考文章:

2.Bitmap加Matrix。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static Drawable resizeImage(Bitmap bitmap, int w, int h)
{
Bitmap BitmapOrg = bitmap;
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return new BitmapDrawable(resizedBitmap);
}

此方法可以随意指定宽高

3.ThumbnailUtils.extractThumbnail(Bitmap source, int width, int height)
我这里使用的是第三种

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
int viewW = mImage.getMeasuredWidth();
int viewH = mImage.getMeasuredHeight();
int imgW = mAdBitmap.getWidth();
int imgH = mAdBitmap.getHeight();
float scale = 0f;
if(imgW>imgH) {
scale = (float)viewW/imgW;
}else {
scale = (float)viewH/imgH;
}
if(scale == 1) {
return true;
}
LogUtils.d(TAG, "scale:"+scale);
int dstW = (int)(imgW*scale);
int dstH = (int)(imgH*scale);
Bitmap tmp = mAdBitmap;
mAdBitmap = ThumbnailUtils.extractThumbnail(tmp, dstW, dstH);
tmp.recycle();
LogUtils.d(TAG, "viewW:"+viewW+";viewH:"+viewH+";imgW:"+imgW+";imgH:"+imgH+";dstW:"+dstW+";dstH:"+dstH);
mImage.setImageBitmap(mAdBitmap);

参考文章:
http://blog.csdn.net/lincyang/article/details/6651582
http://www.android-007.com/?p=249