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

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

	/**
	* @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();
    }


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值