将两张图片合成一张新的图片
/**
* 图片合成
*
* @param backgroundPath 底图
* @param smallPath 小图
* @param type 生成图片类型jpg,png...
* @param resultPath 生成图片保存路径
*/
public static void image(String backgroundPath, String smallPath, String type, String resultPath) {
try {
Assert.hasText(backgroundPath, "底图路径为空");
Assert.hasText(smallPath, "小图路径为空");
BufferedImage small = getBufferedImageFromUrl(smallPath);
BufferedImage image = getBufferedImageFromUrl(backgroundPath);
//生成画笔
Graphics g = image.getGraphics();
g.drawImage(small, 230, 600,
small.getWidth()*2, small.getHeight()*2, null);
ImageIO.write(image, type, new File(resultPath));
} catch (IOException e) {
throw new RuntimeException("合成图片失败", e);
}
/**
* 根据图片url获取图片
*
* @param url
* @return
* @throws IOException
*/
private static BufferedImage getBufferedImageFromUrl(String url) throws IOException {
if (url.startsWith("https://") || url.startsWith("http://")) {
return ImageIO.read(new URL(url));
} else {
return ImageIO.read(new File(url));
}
}
测试类
public static void main(String[] args) {
image("xxx", "xxx", "png", "xxx");
}