Android 开发压缩图片
private Bitmap imageZoom(int position , Bitmap bitMap) {
//图片允许最大空间
double maxSize =2000.00;
double bitmapSize = bitMap.getByteCount()/1024;
Log.d("derrick", "bitmap 0 = "+bitmapSize+" , index = "+position);
if (bitmapSize < maxSize) {
return bitMap;
}
if (bitmapSize > maxSize) {
//获取bitmap大小 是允许最大大小的多少倍
double scale = bitmapSize / maxSize;
//开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小)
Bitmap result = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(scale),bitMap.getHeight() / Math.sqrt(scale));
Log.i("derrick", "bitmap 1 = "+result.getByteCount()/1024 +" , index = "+position);
return result;
}
return bitMap;
}
private Bitmap zoomImage(Bitmap bgimage, double newWidth,double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
return bitmap;
}