Drawable对象转为Bitmap对象
private static Bitmap getBitmap(Drawable drawable) {
//获取drawable高宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
//PixelFormat.OPAQUE:透明度
//Android默认格式是PixelFormat.OPAQUE,其是不带Alpha值的
//这句话的作用在于根据原图的效果来设置,避免光晕
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);
//把bitmap画到画布中
drawable.draw(canvas);
return bitmap;
}
压缩Bitmap
//width、height是我们想要的图片大小
private static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
//获取图片的高宽
int w = bitmap.getWidth();
int h = bitmap.getHeight();
//根据矩阵来重新创建图片
Matrix matrix = new Matrix();
//压缩的比例
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
//设置矩阵的比例
matrix.postScale(scaleWidth, scaleHeight);
//创建新的Bitmap
//0,0表示第一个像素点 w,h表示最后一个像素点, matrix表示最终需要的像素
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}