版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_GLY_di/article/details/53204445
第一种:通过compress
/**
* 图片压缩
*
* @param beforBitmap
* @return
*/
private Bitmap compressImage(Bitmap beforBitmap) {
// 可以捕获内存缓冲区的数据,转换成字节数组。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (beforBitmap != null) {
// 第一个参数:图片压缩的格式;第二个参数:压缩的比率;第三个参数:压缩的数据存放到bos中
beforBitmap.compress(CompressFormat.JPEG, 100, bos);
int options = 100;
// 循环判断压缩后的图片是否是大于100kb,如果大于,就继续压缩,否则就不压缩
while (bos.toByteArray().length / 1024 > 80) {
bos.reset();// 置为空
// 压缩options%
beforBitmap.compress(CompressFormat.JPEG, options, bos);
// 每次都减少10
options -= 10;
}
// 从bos中将数据读出来 存放到ByteArrayInputStream中
ByteArrayInputStream bis = new ByteArrayInputStream(
bos.toByteArray());
// 将数据转换成图片
Bitmap afterBitmap = BitmapFactory.decodeStream(bis);
return afterBitmap;
}
return null;
}
第二种:获取缩略图
/**
* 获得缩略图
* @param bitmap
* @return
*/
public Bitmap getThumbnail(Bitmap bitmap) {
// 宽
int w = bitmap.getWidth();
// 高
int h = bitmap.getHeight();
// 获得缩略图
Bitmap afterBitmap = ThumbnailUtils
.extractThumbnail(bitmap, w, h);
return afterBitmap;
}