java 压缩图片

由于网站需要对上传的图片进行宽度判断缩放和质量压缩,以提升整体加载速度,于是我在网上找处理方法,
网上大多数是谷歌图片处理组件Thumbnails的介绍。最开始我用Thumbnails尝试,但不知道什么原因,没有任何效果,也不报错。
由于时间的关系,就没再深入研究,另寻他路。后来找到了下面的方法,这个方法优点在于完全基于Java自带API,调用也非常简单,如果只是缩放和压缩,这个方法足够了。
/**
     * 缩放图片(压缩图片质量,改变图片尺寸)
     * 若原图宽度小于新宽度,则宽度不变!
     * @param newWidth 新的宽度
     * @param quality 图片质量参数 0.7f 相当于70%质量
     */
    public static void imageResize(File originalFile, File resizedFile,
                              int maxWidth,int maxHeight, float quality) throws IOException {

        if (quality > 1) {
            throw new IllegalArgumentException(
                    "图片质量需设置在0.1-1范围");
        }

        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
        Image i = ii.getImage();
        Image resizedImage = null;

        int iWidth = i.getWidth(null);
        int iHeight = i.getHeight(null);

        int newWidth = maxWidth;
        if(iWidth < maxWidth){
            newWidth = iWidth;
        }


        if (iWidth >= iHeight) {
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
                    / iWidth, Image.SCALE_SMOOTH);
        }



        int newHeight = maxHeight;
        if(iHeight < maxHeight){
            newHeight = iHeight;
        }

        if(resizedImage==null && iHeight >= iWidth){
            resizedImage = i.getScaledInstance((newHeight * iWidth) / iHeight,
                    newHeight, Image.SCALE_SMOOTH);
        }

        // This code ensures that all the pixels in the image are loaded.
        Image temp = new ImageIcon(resizedImage).getImage();

        // Create the buffered image.
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
                temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

        // Copy image to buffered image.
        Graphics g = bufferedImage.createGraphics();

        // Clear background and paint the image.
        g.setColor(Color.white);
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
        g.drawImage(temp, 0, 0, null);
        g.dispose();

        // Soften.
        float softenFactor = 0.05f;
        float[] softenArray = { 0, softenFactor, 0, softenFactor,
                1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
        Kernel kernel = new Kernel(3, 3, softenArray);
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        bufferedImage = cOp.filter(bufferedImage, null);

        // Write the jpeg to a file.
        FileOutputStream out = new FileOutputStream(resizedFile);

        // Encodes image as a JPEG data stream
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

        JPEGEncodeParam param = encoder
                .getDefaultJPEGEncodeParam(bufferedImage);

        param.setQuality(quality, true);

        encoder.setJPEGEncodeParam(param);
        encoder.encode(bufferedImage);
    } // Example usage

原贴:https://www.cnblogs.com/jsper/p/7652896.html

### Java中用于压缩图片的方法或库 在Java中,可以使用多种方法和库来实现图片压缩。以下是几种常见的方法和库: #### 方法一:使用`ImageIO`和`BufferedImage`类 通过`ImageIO`和`BufferedImage`类可以直接操作图片,并将其转换为其他格式(如从PNG转为JPEG),同时改变图片的位深以实现压缩效果[^2]。 ```java import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; public class ImageCompressor { public static void main(String[] args) throws Exception { File input = new File("input.png"); BufferedImage image = ImageIO.read(input); BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); bufferedImage.createGraphics().drawImage(image, 0, 0, null); ImageIO.write(bufferedImage, "jpg", new File("output.jpg")); } } ``` #### 方法二:使用`Thumbnailator`库 `Thumbnailator`是一个功能强大的第三方库,支持图片的尺寸调整和质量压缩。它提供了简单易用的API,能够快速实现图片压缩[^3]。 ```java import net.coobird.thumbnailator.Thumbnails; import java.io.File; import java.io.IOException; public class ThumbnailatorExample { public static void compressImage(String inputPath, String outputPath, float quality) throws IOException { Thumbnails.of(new File(inputPath)) .scale(1.0) .outputQuality(quality) .toFile(new File(outputPath)); } } ``` #### 方法三:使用`Imgscalr`库 `Imgscalr`是另一个流行的第三方库,专注于图片的缩放和压缩。它可以轻松调整图片大小并保持较高的视觉质量[^1]。 ```java import org.imgscalr.Scalr; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ImgscalrExample { public static void compressImage(String inputPath, String outputPath, int quality) throws IOException { BufferedImage originalImage = ImageIO.read(new File(inputPath)); BufferedImage compressedImage = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, quality); ImageIO.write(compressedImage, "jpg", new File(outputPath)); } } ``` #### 方法四:使用`javax.imageio.IIOImage`和`IIOWriteParam` 通过`javax.imageio`包中的`IIOImage`和`IIOWriteParam`类,可以更精细地控制图片压缩质量[^4]。 ```java import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.util.Iterator; public class CustomCompression { public static void compressImage(String inputPath, String outputPath, float quality) throws Exception { BufferedImage image = ImageIO.read(new File(inputPath)); Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); if (!writers.hasNext()) throw new IllegalStateException("No writers found"); ImageWriter writer = writers.next(); ImageOutputStream ios = ImageIO.createImageOutputStream(new FileOutputStream(outputPath)); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); } writer.write(null, new IIOImage(image, null, null), param); ios.close(); writer.dispose(); } } ``` ### 压缩质量参数说明 压缩质量参数通常是一个介于0.0到1.0之间的浮点数,表示压缩的程度。值越接近1.0,图片质量越高,文件体积也越大;值越接近0.0,图片质量越低,但文件体积会显著减小[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值