图片的压缩:
由于Android并没有提供api可以一次性将图片压缩到指定大小,只提供了按压缩比,即:Bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);所以要想压缩到指定大小可以这样做:
/**
* 压缩图片
* @param image
* @return
*/
private byte[] compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
options -= 5;//每次都减少5
image.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
}
// ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
// Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
// return bitmap;
return baos.toByteArray();
}将指定图片压缩到100kb以下。另外,要非常注意,Bitmap.compress()的第一个参数指定的图片类型与实际的图片的类型不一致时,将不会进行压缩,即xxxx.jpg必须用Bitmap.CompressFormat.JPEG,xxx.png必须用Bitmap.CompressFormat.PNG。否则,上面的循环压缩中将出现死循环。
图片的缩放:
/**
* 按宽度缩放图片
* @param bitmap 待缩放的Bitmap
* @param w 要缩放到的宽度
* @return
*/
public static Bitmap resizeBitmap_width(Bitmap bitmap, int w) {
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleSize = ((float) w) / width;//计算宽度比,如果按高度缩放应是((float) h) / height
Matrix matrix = new Matrix();
matrix.postScale(scaleSize, scaleSize);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return resizedBitmap;
} else {
return null;
}
}