图片质量压缩,尺寸不变,不需要用到磁盘
2017-06-20 12:21
316 查看
项目遇到一个很刁钻的问题,系统有个上传图片的功能,但是为了节省带宽,必须限制用户输入图片的大小,为了用户的体验,用户上传任意一张图片都要被允许,并且不能使用磁盘。这个刁钻的问题解决方法只有在用户上传图片的时候,如果图片大小超过一定的时候就自行质量压缩,尺寸维持不变,代码如下,完美解决问题
下面是安卓端的方式
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();
}
/** * @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();
}
相关文章推荐
- 【No4.】对图片的压缩质量、压缩尺寸、读流压缩、方法介绍
- Android图片压缩(质量压缩和尺寸压缩)、图片保存(本地和sqlite数据库)
- 网页图片的压缩——保持尺寸不变,减小图片大小
- 性能优化之图片压缩(质量压缩、尺寸压缩)
- java 程序实现对图片的压缩生成缩略图并可设定长宽、尺寸压缩率、图片质量
- 图片尺寸、质量压缩
- java 程序实现对图片的压缩生成缩略图并可设定长宽、尺寸压缩率、图片质量
- 一种使用GDI+对图片尺寸和质量的压缩方法
- 同等尺寸下为何android压缩出来的图片质量不如iphone
- java 程序实现对图片的压缩生成缩略图并可设定长宽、尺寸压缩率、图片质量
- Android图片压缩,质量压缩和尺寸压缩两种
- Android进阶——图片优化之质量压缩、尺寸压缩、采样率压缩、LibJpeg压缩
- Android图片压缩尺寸和质量
- 图片尺寸压缩和图片质量压缩
- java 程序实现对图片的压缩生成缩略图并可设定长宽、尺寸压缩率、图片质量
- Golang 编写的图片压缩程序,质量、尺寸压缩,批量、单张压缩
- Android图片压缩尺寸及质量
- 传统基础图片压缩:先尺寸压缩后质量压缩
- iOS开发中压缩图片的质量以及缩小图片尺寸
- 安卓图片的压缩,尺寸,质量,采样率和微信压缩