一、说明
若干张图片,一张是背景,其它图片需要合成到背景图中。
二、图片简单整合
素材
代码
/**
* @param backgroundPath 背景图片
* @param targetPath 添加的图片
* @param outPutPath 输出路径
* @param x 添加位置坐标
* @param y 添加位置坐标
* @param width 图片大小
* @param height 图片大小
* @return
*/
public static File combinationImage(String backgroundPath,
String targetPath,
String outPutPath,
int x,
int y,
int width,
int height) {
try {
//背景底图设置图片大小
BufferedImage background = ImageIO.read(new File(backgroundPath));
//添加的图片
BufferedImage image = resizeBufferedImage(width, height, ImageIO.read(new File(targetPath)));
//在背景图片上添加图片
Graphics2D g = background.createGraphics();
g.drawImage(image, x, y, image.getWidth(), image.getHeight(), null);
// 关闭 Graphics2D 上下文
g.dispose();
File out = new File(outPutPath + System.currentTimeMillis() + ".jpg");
ImageIO.write(background, "jpg", out);
return out;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param newWidth 新的宽度和高度(单位:像素)
* @param newHeight 新的宽度和高度(单位:像素)
* @param bfi
* @return
* @throws IOException
*/
public static BufferedImage resizeBufferedImage(int newWidth, int newHeight, BufferedImage bfi) {
Image image = bfi.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
// 创建 Graphics2D 对象,用于进行缩放操作
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) resizedImage.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return resizedImage;
}
public static void main(String[] args) {
combinationImage("D:\\work\\图像识别\\AI图像素材\\扫码支付背景.jpg"</