一、代码
public static byte[] compressorImage(byte[] bytes, long size, int targetSize) {final long convertValue = 1024L;long convertTargetSize = targetSize * convertValue;if (size < convertTargetSize) {return bytes;}try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) {BufferedImage sourceImage = ImageIO.read(bis);double scaleFactor = Math.sqrt(convertTargetSize / (double) size);int targetWidth = 4096;int targetHeight = targetWidth * sourceImage.getHeight() / sourceImage.getWidth();BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g2d = targetImage.createGraphics();g2d.drawImage(sourceImage, 0, 0, null);g2d.dispose();ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();ImageWriteParam param = writer.getDefaultWriteParam();param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);param.setCompressionQuality((float) scaleFactor);try (ByteArrayOutputStream bos = new ByteArrayOutputStream();ImageOutputStream ios = ImageIO.createImageOutputStream(bos)) {writer.setOutput(ios);writer.write(null, new IIOImage(targetImage, null, null), param);ios.flush();writer.dispose();return bos.toByteArray();}} catch (Exception e) {log.error("compressorImage err", e);}return new byte[0];}