前言
在开发过程中,有时候想要将一张图片在另外一张图片居中显示,可以采取一下做法
图片居中显示
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageCenterDisplayDemo {
static void main() {
try {
// 1. 加载子图像(要居中显示的图像)
BufferedImage subImage = ImageIO.read(new File("D:\temp\2.png"));
// 2. 创建父图像(画布,这里创建800x600的空白图像,也可以加载现有图像)
int parentWidth = 2000;
int parentHeight = 2000;
BufferedImage parentImage = new BufferedImage(parentWidth, parentHeight, BufferedImage.TYPE_INT_RGB);
// 3. 调用方法将子图像居中绘制到父图像
BufferedImage resultImage = drawImageCentered(parentImage, subImage);
// 4. 保存结果图像(可选)
ImageIO.write(resultImage, "PNG", new File("d:/result.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将子图像居中绘制到父图像上
*
* @param parentImage 父图像(画布)
* @param subImage 子图像(要居中的图像)
* @return 绘制后的图像
*/
public static BufferedImage drawImageCentered(BufferedImage parentImage, BufferedImage subImage) {
// 获取父图像和子图像的宽高
int parentW = parentImage.getWidth();
int parentH = parentImage.getHeight();
int subW = subImage.getWidth();
int subH = subImage.getHeight();
// 计算居中坐标(水平居中x,垂直居中y)
int x = (parentW - subW) / 2;
int y = (parentH - subH) / 2;
// 获取Graphics2D对象(用于绘制)
Graphics2D g2d = parentImage.createGraphics();
try {
// 开启抗锯齿(可选,让图像边缘更平滑)
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// 绘制子图像到居中坐标
g2d.drawImage(subImage, x, y, null);
} finally {
// 释放资源
g2d.dispose();
}
return parentImage;
}
}
结果为
总结
可以使用以上方法将图片居中显示