我正在使用Java存储和修改.jpg图像(不是安卓或Swing)。我想转换一个新尺寸的图像,保持高宽比,如果新尺寸与原始图像不成比例,则用白色填充背景。
BufferedImage image = /*Here i read from disk and load the image */;
image = resizeImage(image, newWidth, newHeight);
ImageIO.write(image, extension, new File(filename + "_" + page + "." + extension));
我正在尝试实现的函数是resizeImage:在示例中调整图像大小,但它不保持高宽比。
private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
我想一张照片会更能说明我想要的是什么:
如果原始图像为200x200,并被要求将大小调整到400x300,则结果应该是一幅具有白色边距的图片,并且原始图像在内部调整大小。在本例中,应该是300x300。
问题不是如何调整大小,而是如何用白色填充剩馀的图像,以及中心的原始大小调整的图像。
发布于 2022-06-10 18:36:36
这段代码适用于我:
private static BufferedImage resizeImage(BufferedImage originalImage, int newWidth, int newHeight) {
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
Graphics2D graphics = resizedImage.createGraphics();
graphics.setColor(Color.WHITE);
// fill the entire picture with white
graphics.fillRect(0, 0, newWidth, newHeight);
int maxWidth = 0;
int maxHeight = 0;
// go along the width and height in increments of 1 until one value is equal to the specified resize value
while (maxWidth <= newWidth && maxHeight <= newHeight)
{
++maxWidth;
++maxHeight;
}
// calculate the x value with which the original image is centred
int centerX = (resizedImage.getWidth() - maxWidth) / 2;
// calculate the y value with which the original image is centred
int centerY = (resizedImage.getHeight() - maxHeight) / 2;
// draw the original image
graphics.drawImage(originalImage, centerX, centerY, maxWidth, maxHeight, null);
graphics.dispose();
return resizedImage;
}
在此之前:
之后:
https://stackoverflow.com/questions/72577436
复制相似问题