用H5调用原生的上传后,图片需要压缩,我终合网上的几种方法,发现按比例压缩失真度较小,也很好用,特上传出来,让大家看看
/**
* 压缩方法通用
* @param image
* @param size 我自己填的是250,一般可以保证图片大小在1M以下
*/
public static Bitmap compressImage(Bitmap image,int size){
ByteArrayOutputStream out = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 85, out);
float zoom = (float)Math.sqrt(size * 1024 / (float)out.toByteArray().length);
Matrix matrix = new Matrix();
matrix.setScale(zoom, zoom);
Bitmap result = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, true);
out.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, out);
while(out.toByteArray().length > size * 1024){
matrix.setScale(0.9f, 0.9f);
result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
out.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, out);
}
return result;
}