我有一个调整大小的图像:
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 图像来包含缩放后的新图像。像这样的事情:
我尝试了一些事情,但没有达到预期的效果。 如有任何帮助,我们将不胜感激。
最佳答案
我们开始:
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/