Java 图片压缩

1.引入包

        <!--thumbnailator图片处理 压缩 裁剪 工具-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

2.工具类

/**
 * @description: 图片上传工具类
 */
@Component
public class UploadCodeUtils {

    /**
     * @Description: 压缩比值,可以随意调节
     * @Return: null
     **/
    private static final Logger logger = LoggerFactory.getLogger(UploadCodeUtils.class);
    private static final Integer ZERO = 0;
    private static final Integer ONE_ZERO_TWO_FOUR = 1024;
    private static final Integer TWO_ZERO_FOUR_EIGHT = 2048;
    private static final Integer NINE_ZERO_ZERO = 900;
    private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
    private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
    private static final Double ZERO_EIGHT_FIVE = 0.85;
    private static final Double ZERO_SIX = 0.6;
    private static final Double ZERO_FOUR_FOUR = 0.44;
    private static final Double ZERO_FOUR = 0.4;


    /**
     * @Description: 根据指定大小压缩图片
     * @Param [imageBytes:源图片字节数组, desFileSize:指定图片大小,单位kb]
     * @Return: byte[] 压缩后的图片字节数组
     **/
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
        if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
        try {
            while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
            logger.info("图片原大小={}kb | 压缩后大小={}kb",
                    srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
        } catch (Exception e) {
            logger.error("图片压缩失败!", e);
        }
        return imageBytes;
    }

    /**
     * @Description: 自动调节精度(经验数值),按照图划分4级
     * @Param [size:源图片大小]
     * @Return: double 图片压缩质量比
     **/
    private static double getAccuracy(long size) {
        double accuracy;
        //判断图片大小 进行等比例压缩
        if (size < NINE_ZERO_ZERO) {
            accuracy = ZERO_EIGHT_FIVE;
        } else if (size < TWO_ZERO_FOUR_SEVEN) {
            accuracy = ZERO_SIX;
        } else if (size < THREE_TWO_SEVEN_FIVE) {
            accuracy = ZERO_FOUR_FOUR;
        } else {
            accuracy = ZERO_FOUR;
        }
        return accuracy;
    }

    /**
     * @Description: byte数组 转 InputStream
     * @Param [bytes]
     * @Return: java.io.InputStream
     **/
    public static InputStream byteToInputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }


    /**
     * @Description: InputStream 转 byte数组
     * @Param [inputStream]
     * @Return: byte[]
     **/
    public static byte[] inputStreamToByte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}

Java 中可以使用 ImageIO 类和 BufferedImage 类来进行图片压缩操作。以下是一个简单的示例代码: ```java import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageCompressor { public static void main(String[] args) throws IOException { File inputFile = new File("input.jpg"); BufferedImage inputImage = ImageIO.read(inputFile); int maxWidth = 800; int maxHeight = 600; Dimension newDimension = getScaledDimension(new Dimension(inputImage.getWidth(), inputImage.getHeight()), new Dimension(maxWidth, maxHeight)); BufferedImage outputImage = new BufferedImage(newDimension.width, newDimension.height, BufferedImage.TYPE_INT_RGB); outputImage.getGraphics().drawImage(inputImage.getScaledInstance(newDimension.width, newDimension.height, Image.SCALE_SMOOTH), 0, 0, null); File outputFile = new File("output.jpg"); ImageIO.write(outputImage, "jpg", outputFile); } public static Dimension getScaledDimension(Dimension imageSize, Dimension boundary) { int width = imageSize.width; int height = imageSize.height; int maxWidth = boundary.width; int maxHeight = boundary.height; double ratio = Math.min((double) maxWidth / width, (double) maxHeight / height); return new Dimension((int) (width * ratio), (int) (height * ratio)); } } ``` 上述代码中,首先读取一张图片(假设为 input.jpg),然后指定最大宽度和最大高度进行压缩。使用 `getScaledDimension` 方法计算新的宽度和高度,然后创建一个新的 `BufferedImage` 对象并将原始图片缩放到新的尺寸,最后将新的图片保存到文件中(假设为 output.jpg)。 需要注意的是,这里使用的是 `Image.SCALE_SMOOTH` 参数,表示使用平滑缩放算法,可以得到更好的压缩效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值