图片压缩

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PicUtil {

    public static void main(String[] args) {
        String picInSrc = "F:\\pic\\background.bmp";
        String picOutSrc = "F:\\pic\\new.bmp";
        compressPic(picInSrc, picOutSrc, 0.3);
    }

    /**
     * 图片缩放
     * @param picInSrc 待压缩图片全路径    例: D:\test\pic.bmp
     * @param picOutSrc 压缩后图片全路径   例: D:\test\picNew.bmp
     * @param scale 缩放比
     * @return
     */
    public static boolean compressPic(String picInSrc, String picOutSrc, double scale) {
        try {
            File picIn = new File(picInSrc);
            File picOut = new File(picOutSrc);
            // 若图片不存在
            if (!picIn.exists()) {
                System.out.println("The original image does not exist!");
                return false;
            }
            // 读取图片
            Image src = ImageIO.read(picIn);
            // 若图片格式不对或获取不到宽度
            if (src == null || src.getWidth(null) == -1) {
                System.out.println("image type problem!");
                return false;
            }
            // 宽度 * 缩放比
            int width = (int) (src.getWidth(null) * scale);
            // 高度 * 缩放比
            int height = (int) (src.getHeight(null) * scale);
            System.out.println("w:" + width);
            System.out.println("h:" + height);

            /* java提供了4个缩放的微调选项

             * image.SCALE_SMOOTH //平滑优先

             * image.SCALE_FAST//速度优先

             * image.SCALE_AREA_AVERAGING //区域均值

             * image.SCALE_REPLICATE //像素复制型缩放

             * image.SCALE_DEFAULT //默认缩放模式

             * */

            // 绘制图片
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            bufferedImage.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            FileOutputStream out = new FileOutputStream(picOut);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(bufferedImage);
            out.close();
            // 压缩成功
            System.out.println("photo compression success!");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

}

 

引自https://blog.csdn.net/weixin_34966742/article/details/114071394

posted @ 2022-02-07 14:08  小狗吃月亮  阅读(35)  评论(0编辑  收藏  举报