gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:53:32 30 4
gpt4 key购买 nike

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

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

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

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 图像来包含缩放的新图像。像这样的东西: 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/10245220/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com