调整图片大小,保持纵横比

77

我有一张需要调整大小的图片:

if((width != null) || (height != null))
{
    try{
        // Scale image on disk
        BufferedImage originalImage = ImageIO.read(file);
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                                                : originalImage.getType();

        BufferedImage resizedImageJpg = resizeImage(originalImage, type, 200, 200);
        ImageIO.write(resizedImageJpg, "jpg", file); 

       } catch(IOException e) {
           System.out.println(e.getMessage());
       }
}

这是我调整图像大小的方式:

private static BufferedImage resizeImage(BufferedImage originalImage, int type,
                                         Integer imgWidth, Integer imgHeight)
{
    var resizedImage = new BufferedImage(imgWidth, imgHeight, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, imgWidth, imgHeight, null);
    g.dispose();

    return resizedImage;
}

现在的问题是,我还需要保持纵横比。也就是说,我需要新的200/200图像包含新的缩放图像。类似于这样: enter image description here

我尝试了一些方法,但它们并没有如预期那样奏效。 非常感谢您的帮助。

11个回答

-3

只需在Ozzy的代码中添加一个块,使其看起来像这样:

public static Dimension getScaledDimension(Dimension imgSize,Dimension boundary) {

    int original_width = imgSize.width;
    int original_height = imgSize.height;
    int bound_width = boundary.width;
    int bound_height = boundary.height;
    int new_width = original_width;
    int new_height = original_height;

    // first check if we need to scale width
    if (original_width > bound_width) {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }

    // then check if we need to scale even with the new height
    if (new_height > bound_height) {
        //scale height to fit instead
        new_height = bound_height;
        //scale width to maintain aspect ratio
        new_width = (new_height * original_width) / original_height;
    }
    // upscale if original is smaller
    if (original_width < bound_width) {
        //scale width to fit
        new_width = bound_width;
        //scale height to maintain aspect ratio
        new_height = (new_width * original_height) / original_width;
    }

    return new Dimension(new_width, new_height);
}

你只是简单地复制了第一个条件语句,然后将其粘贴到第二个之后... -_- - ZZZZtop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接