您的位置:首页 > 其它

图片质量压缩,尺寸不变,不需要用到磁盘

2017-06-20 12:21 316 查看
项目遇到一个很刁钻的问题,系统有个上传图片的功能,但是为了节省带宽,必须限制用户输入图片的大小,为了用户的体验,用户上传任意一张图片都要被允许,并且不能使用磁盘。这个刁钻的问题解决方法只有在用户上传图片的时候,如果图片大小超过一定的时候就自行质量压缩,尺寸维持不变,代码如下,完美解决问题

/**
* @Title: compressPic
* @Description: 压缩图片,通过压缩图片质量,保持原图大小
* @param  quality:0-1
* @return byte[]
* @throws
*/
public static byte[] compressPic(byte[] imageByte,float quality) {
byte[] inByte = null;
try {
ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
Image img = ImageIO.read(byteInput);
float newWidth = img.getWidth(null);
float newHeight = img.getHeight(null);
Image image = img.getScaledInstance((int) newWidth,(int) newHeight, Image.SCALE_SMOOTH);
// 缩放图像
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = tag.createGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream(imageByte.length);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(tag);
/* 压缩质量 */
jep.setQuality(quality, true);
encoder.encode(tag, jep);
inByte = out.toByteArray();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return inByte;
}


下面是安卓端的方式

public static byte[] compressImage(Bitmap image,int size,int options) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
return baos.toByteArray();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: