[英]Resize Java BufferedImage keeping aspect ratio and fill with background
我正在使用 Java 來存儲和修改 .jpg 圖像(不是 Android 或 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。
問題不在於如何調整大小,而在於如何用白色填充剩余的圖像,並將原始調整大小的圖像放在它的中心。
這段代碼對我有用:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.