Java图像调整大小,保持纵横比 [英] Java image resize, maintain aspect ratio

查看:705
本文介绍了Java图像调整大小,保持纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an image which I resize:

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 resizeImageJpg = resizeImage(originalImage, type, 200, 200);
        ImageIO.write(resizeImageJpg, "jpg", file); 

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

这是我调整图片大小的方法:

This is how I resize the image:

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

    return resizedImage;
}

现在的问题是,我还需要保持宽高比。也就是说,我需要新的200/200图像来包含缩放的新图像。这样的事情:

Now the problem is, I also need to maintain aspect ratio. That is, I need the new 200/200 image to contain the new image scaled. Something like this:

我尝试了一些东西,但是他们没有按预期工作。
任何帮助表示赞赏。非常感谢。

I tried some things but they didn't work out as expected. Any help is appreciated. Thanks alot.

推荐答案

我们走了:

Dimension imgSize = new Dimension(500, 100);
Dimension boundary = new Dimension(200, 200);

根据边界返回新尺寸的功能

Function to return the new size depending on the boundary

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;
    }

    return new Dimension(new_width, new_height);
}

如果有人还需要图片大小调整代码,这是一个不错的解决方案

In case anyone also needs the image resizing code, here is a decent solution.

如果您不确定上述解决方案有不同的方法来实现相同的结果。

If you're unsure about the above solution there are different ways to achieve the same result.

这篇关于Java图像调整大小,保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆