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实现图片压缩一般有两种方式: - **使用Graphics + 文件格式转换框架**:这种方式比较麻烦,代码量多一些,不过压缩出的图片质量会更好 [^1]。虽然引用中未给出具体代码示例,但在实际开发中,这种方式会涉及到使用Java的`Graphics`类进行图像的绘制和处理,同时结合文件格式转换框架来完成图片压缩。 - **使用Google的开源框架thumbnailator**:这种方式不需要写太多的代码就可以实现快速的图片压缩 [^1]。示例代码如下,展示了将图片指定输出格式为"jpg"并进行压缩的操作: ```java import net.coobird.thumbnailator.Thumbnails; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; public class ImageCompressionExample { public static void main(String[] args) { try { File tempFile = new File("path/to/your/image"); ByteArrayOutputStream os = new ByteArrayOutputStream(); // 指定输出格式为"jpg",转换文件格式 Thumbnails.of(tempFile) .size(1024, 1024) .outputFormat("jpg") .outputQuality(0.5) .toOutputStream(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,`outputQuality`参数用于控制图片压缩过程中的质量,压缩质量通常以一个浮点数表示,范围从0.0(最低质量,最大压缩)到1.0(最高质量,最小压缩或无损压缩,但对于大多数有损压缩格式如JPEG来说,即使设置为1.0,仍然是有损的) [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值