bitmap 缩放

按比例缩放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 /**
*
* @param bmp 原 bitmap
* @param ratio 缩放比例
* @return
*/
public static Bitmap sizeCompress(Bitmap bmp, int ratio) {
Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Rect rect = new Rect(0, 0, bmp.getWidth() / ratio, bmp.getHeight() / ratio);

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setAlpha(70); //透明度
// paint.setColorFilter(new LightingColorFilter(16777215, 13369344));
canvas.drawBitmap(bmp, (Rect)null, rect, paint);
// canvas.drawColor(Color.TRANSPARENT); //设置背景为透明
return result;
}

指定缩放后大小

1
2
3
4
5
6
7
8
9
10
11
public static Bitmap sizeCompress(Bitmap bmp, int width, int height) {
int w = bmp.getWidth();
int h = bmp.getHeight();
// 定义矩阵对象
Matrix matrix = new Matrix();
// 缩放原图
matrix.postScale((float) width/w, (float) height/h);
//bmp.getWidth(), bmp.getHeight()分别表示缩放后的位图宽高
Bitmap result = Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);
return result;
}

drawableToBitmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static Bitmap drawableToBitmap(Drawable drawable) {
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();

// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}

Drawable缩放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
// drawable转换成bitmap
Bitmap oldbmp = drawableToBitmap(drawable);
// 创建操作图片用的Matrix对象
Matrix matrix = new Matrix();
// 计算缩放比例
float sx = ((float) w / width);
float sy = ((float) h / height);
// 设置缩放比例
matrix.postScale(sx, sy);
// 建立新的bitmap,其内容是对原bitmap的缩放后的图
Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,matrix, true);
return new BitmapDrawable(newbmp);
}