• java 图片压缩


    1.用户上传图片太大,前端浏览时出现卡顿,故上传后对图片进行压缩

    package net.eoutech.uuwifi.ws.commons.utils;
    
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.image.ColorModel;
    import java.awt.image.ConvolveOp;
    import java.awt.image.Kernel;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class ImagesFilerUtil {
    
        /**
         * 缩放图片(压缩图片质量,改变图片尺寸)
         * 若原图宽度小于新宽度,则宽度不变!
         * @param originalFile 原图片路径地址
         * @param resizedFile 压缩后输出路径地址
         * @param maxWidth 最大宽度
         * @param maxHeight 最大高度
         * @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);
            }
    
            //此代码确保加载图像中的所有像素
            Image temp = new ImageIcon(resizedImage).getImage();
    
            //创建缓冲图像
            BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
                    temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
    
            //将图像复制到缓冲图像
            Graphics g = bufferedImage.createGraphics();
    
            //清除背景并绘制图像。
            g.setColor(Color.white);
            g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
            g.drawImage(temp, 0, 0, null);
            g.dispose();
    
    
            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);
    
            //将jpeg写入文件
            FileOutputStream out = new FileOutputStream(resizedFile);
    
            //将图像编码为jpeg数据流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
    
            param.setQuality(quality, true);
    
            encoder.setJPEGEncodeParam(param);
            encoder.encode(bufferedImage);
        }
    
    
    //方法二
    
        public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException {
            File file = null;
            BufferedImage src = null;
            FileOutputStream out = null;
            ImageWriter imgWrier;
            ImageWriteParam imgWriteParams;
    
            // 指定写图片的方式为 jpg
            imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
            imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
            // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
            imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
            // 这里指定压缩的程度,参数qality是取值0~1范围内,
            imgWriteParams.setCompressionQuality((float) 0.5);
            
            imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
            ColorModel colorModel =ImageIO.read(new File(srcFilePath)).getColorModel();// ColorModel.getRGBdefault();
            // 指定压缩时使用的色彩模式
            // imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
    //                colorModel, colorModel.createCompatibleSampleModel(16, 16)));
            imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));
    
            try {
                if (isBlank(srcFilePath)) {
                    return false;
                } else {
                    file = new File(srcFilePath);System.out.println(file.length());
                    src = ImageIO.read(file);
                    out = new FileOutputStream(descFilePath);
    
                    imgWrier.reset();
                    // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
                    // OutputStream构造
                    imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                    // 调用write方法,就可以向输入流写图片
                    imgWrier.write(null, new IIOImage(src, null, null),
                            imgWriteParams);
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }finally {
        try {
    if(out!=null) out.close();
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    }
    
    
    return true;
        }
        public static boolean isBlank(String string) {
            if (string == null || string.length() == 0 || string.trim().equals("")) {
                return true;
            }
            return false;
        }
    
    
    
    
    }

    调用

    ImagesFilerUtil.compressPic(path,path);
    ImagesFilerUtil.zipImageFile(new File(path),new File(path),500,500,0.5f);

  • 相关阅读:
    SQL数据去重复 Distinct 和 row_number() over()
    Excel闪退问题解决
    SQL Server 修改服务器登录名称以及密码
    从底层角度看ASP.NET-A low-level Look at the ASP.NET Architecture
    MD5加密
    MD5实例化异常 未能执行FIPS验证加密算法
    JDBC(上)
    自学MySQL第二天
    自学MySQL第一天
    自学JavaWeb第五天jQuery进阶
  • 原文地址:https://www.cnblogs.com/dztHome/p/14468612.html
Copyright © 2020-2023  润新知