如何将前端上传的图片等比压缩

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

public class ImageResizer {

    public static void resizeImage(InputStream inputStream, int width, int height, String outputPath) throws IOException {
        BufferedImage originalImage = ImageIO.read(inputStream);

        // 计算新的宽度和高度
        int newWidth = originalImage.getWidth();
        int newHeight = originalImage.getHeight();

        if (width > 0 && height > 0) {
            double ratioWidth = (double) width / originalImage.getWidth();
            double ratioHeight = (double) height / originalImage.getHeight();
            double ratio = Math.min(ratioWidth, ratioHeight);

            newWidth = (int) (originalImage.getWidth() * ratio);
            newHeight = (int) (originalImage.getHeight() * ratio);
        }

        // 创建新的BufferedImage
        BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

        // 绘制压缩后的图像
        resizedImage.getGraphics().drawImage(originalImage, 0, 0, newWidth, newHeight, null);

        // 保存到文件
        ImageIO.write(resizedImage, "jpg", new File(outputPath));
    }

    public static void main(String[] args) {
        // 假设这是从前端接收到的文件
        InputStream inputStream = getInputStreamForImage();

        // 设置目标宽度和高度
        int width = 300;
        int height = 200;

        // 设置输出路径
        String outputPath = "/path/to/output/image.jpg";

        try {
            resizeImage(inputStream, width, height, outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 这里是一个假设的函数,用于获取文件流
    private static InputStream getInputStreamForImage() {
        // 这里应该有一个逻辑来获取文件的输入流
        return null;
    }
}

 

点赞

当前页面评论已关闭。

隐藏
变装