java压缩图片

java压缩图片

 

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
 
public class ImageResizer {
 
    public static void resizeImage(String inputImagePath, String outputImagePath, int targetWidth, int targetHeight) throws IOException {
        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);
 
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = outputImage.createGraphics();
 
        // 缩放图片
        Image img = inputImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
        g2d.drawImage(img, 0, 0, null);
        g2d.dispose();
 
        // 输出图片
        ImageIO.write(outputImage, "jpg", new File(outputImagePath));
    }
 
    public static void main(String[] args) {
        try {
            resizeImage("input.jpg", "output.jpg", 100, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

#################

posted @ 2024-04-03 22:28  西北逍遥  阅读(20)  评论(0编辑  收藏  举报