Java 图片压缩 (base64编码)

/**
	 * 压缩base64编码图片,并返回base64
	 * @param base64Image     需要压缩的图片
	 * @param compressSize    压缩大小,传入多少就压缩到该值范围内 (例:524,288 等于 512kb)
	 * @return                返回base64编码
	 * @throws Exception      异常处理
	 */
	public String compressBase64Image(String base64Image, Integer compressSize) throws Exception {

		String newBase64;

		// 判断格式
		if(base64Image.startsWith("data:image")){
			int index = base64Image.indexOf("base64,");
			if(index == -1){
				throw new Exception("无效base64照片格式");
			}
			newBase64 = base64Image.substring(index + 7);
		} else{
			newBase64 = base64Image;
		}

		// replace(" ", "+")
		newBase64 = newBase64.replace(" ", "+");

		// 解码Base64字符串为字节数组
		byte[] imageBytes = Base64.getDecoder().decode(newBase64);

		//  缓冲图像
		BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

		//  根据指定的图像及宽、高按比例缩放并进行压缩质量90%新建缓冲图像缩略图
		BufferedImage image = Thumbnails.of(bufferedImage).size(bufferedImage.getWidth() / 2,
				bufferedImage.getHeight() / 2).outputQuality(0.9).asBufferedImage();

		// 创建输出流对象
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		// 根据传入图像,图像类型,写入指定的输出流中
		ImageIO.write(image, "jpg", outputStream);

		// 输出流转换成字节数组
		imageBytes = outputStream.toByteArray();

		// 使用 Base64 编码方案将指定的字节数组转为 String
        String base64 = Base64.getEncoder().encodeToString(imageBytes);

		// 根据String对象长度判断是否需要进行压缩
		if (base64.length() - base64.length() / 8 * 2 > compressSize) {

			// 设置图像的缩放系数并创建图像 (默认1.0 代表缩略100%)
			image = Thumbnails.of(image).scale(1.0 / base64.length() / compressSize).asBufferedImage();

			// 根据传入图像,图像类型,写入指定的输出流中
			ImageIO.write(image, "jpg", outputStream);

			// 使用 Base64 编码方案将指定的字节数组转为 String
			base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
		}

		// 关闭流
		outputStream.flush();
		outputStream.close();

		// 返回Base64编码图片
		return base64;
	}

其他具体操作自行搜索 Thumbnails 库

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值