我遇到了这个问题: How to scale a Graphics2D image with transparent padding
参考 https://pastebin.com/eFarSKqi
并且我目前正在使用代码,以便可以将其转换为不会重新缩放图像的内容,而只是将其填充。
例如,我有一个500x400像素的图像,那么我需要padd,假设每侧100像素,而无需重新缩放实际图像。
我该怎么做?
用于编辑的基本方法:
public static BufferedImage scaleWithPadding(BufferedImage img, int newWidth, int newHeight) {
int currentWidth = img.getWidth();
int currentHeight = img.getHeight();
int scaledWidth;
int scaledHeight;
if (currentWidth == 0 || currentHeight == 0
|| (currentWidth == newWidth && currentHeight == newHeight)) {
return img;
} else if (currentWidth == currentHeight) {
scaledWidth = newWidth;
scaledHeight = newHeight;
} else if (currentWidth >= currentHeight) {
scaledWidth = newWidth;
double scale = (double) newWidth / (double) currentWidth;
scaledHeight = (int) Math.round(currentHeight * scale);
} else {
scaledHeight = newHeight;
double scale = (double) newHeight / (double) currentHeight;
scaledWidth = (int) Math.round(currentWidth * scale);
}
int x = (newWidth - scaledWidth) / 2;
int y = (newHeight - scaledHeight) / 2;
Color transp = new Color(0, 0, 0, 0);
BufferedImage newImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImg.createGraphics();
g.setColor(transp);
g.fillRect(0, 0, newWidth, newHeight);
g.drawImage(img, x, y, x + scaledWidth, y + scaledHeight, 0, 0, currentWidth, currentHeight,
transp, null);
g.dispose();
return newImg;
}