java生成缩略图的方法,带最大宽度和最大高度参数

搜到有很多方法,按比例缩放后,图片都会变形和失真,假如使用下面这个函数则不会。因为宽和高不是固定死的。

下面这个例子,它缩放完后,宽度和高度都不会超过设定的阈值,假如超出阈值,会自动进行按比例缩放。因此,图片不会失真。

java生成缩略图的方法,输入图片的本地路径、最大宽度和最大高度。

假如宽度和高度任意一个超过阈值,都会对图片进行按比例缩放。

` public static void resizeImage(String originalPath, int maxWidth, int maxHeight) throws IOException {
File originalFile = new File(originalPath);
BufferedImage originalImage = ImageIO.read(originalFile);

    int originalWidth = originalImage.getWidth();
    int originalHeight = originalImage.getHeight();

    // 检查是否需要缩放
    if (originalWidth <= maxWidth && originalHeight <= maxHeight) {
        return; // 无需处理
    }

    // 计算缩放比例
    double widthRatio = (double) maxWidth / originalWidth;
    double heightRatio = (double) maxHeight / originalHeight;
    double ratio = Math.min(widthRatio, heightRatio);

    // 计算新尺寸
    int newWidth = (int) (originalWidth * ratio);
    int newHeight = (int) (originalHeight * ratio);

    // 执行缩放
    BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = resizedImage.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
    graphics.dispose();

    // 获取文件扩展名
    String formatName = originalPath.substring(originalPath.lastIndexOf(".") + 1);

    try {
        // 覆盖原文件
        ImageIO.write(resizedImage, formatName, originalFile);
    }catch (Exception e){

    }
}`

最后保存之后,它会覆盖原来的图片文件。

posted @ 2025-10-29 15:54  十一何十一  阅读(0)  评论(0)    收藏  举报