java - 调整图像大小,保持纵横比

标签 java image rescale

我有一个调整大小的图像:

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

我尝试了一些事情,但没有达到预期的效果。 如有任何帮助,我们将不胜感激。

最佳答案

我们开始:

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

根据边界返回新大小的函数:

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

如果有人还需要图像调整大小代码,here is a decent solution .

如果您对上述解决方案不确定,there are different ways达到相同的结果。

关于java - 调整图像大小,保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15587744/

相关文章:

python - 将 2D numpy 数组重新缩放为密集表示

c# - 在 Windows 窗体中重新缩放图像

java - Collection.sort 与 LinkedList Comparable 方法已被重写

java - 平铺 map 上的 LibGDX AStar 寻路

java - 如何使用 getRGB 在 Java 中匹配相似的颜色

c# - 如何使用 JavaScript 和 ASP.NET MVC 更新图像?

html - 使图像响应(使用浏览器调整大小)

java - 向对象添加点而不覆盖现有点

java - 查找两个字符串中不同的字符

Javascript 剪贴板 API write() 在 Safari 中不起作用