背景
在之前的文章当中我们已经说过【二维码】——生成解析,可是现实中需要将二维码合成到海报的指定位置中,这样来扩展我们的产品销售渠道,基于这样的一种需求我们就需要将之前的二维码合成到另外一张海报图片中,所以接下来说一说怎么合成两张图片
一、代码
/**
* @author 2019/6/23 15:32
*/
@Slf4j
public class MergeImg {
private BufferedImage getImageFromLocal(String path) throws IOException {
return ImageIO.read(new File(path));
}
private BufferedImage mergeImage(BufferedImage img1, BufferedImage img2) {
if (!StringUtils.isEmpty(img1) && !StringUtils.isEmpty(img2)) {
int width = img1.getWidth();
int height = img1.getHeight();
Graphics2D graphics2D = img2.createGraphics();
graphics2D.drawImage(img1, 380, 412, width, height, null);
graphics2D.dispose();
}
return img2;
}
private void writeImageToLocal(String newPath, BufferedImage img) throws IOException {
if (!StringUtils.isEmpty(newPath) && !StringUtils.isEmpty(img)) {
ImageIO.write(img, "png", new File(newPath));
}
}
public void saveMergeImage(String path1, String path2, String newPath) {
log.info("合成图片开始");
try {
writeImageToLocal(newPath, mergeImage(getImageFromLocal(path1), getImageFromLocal(path2)));
log.info("合成图片结束");
} catch (IOException e) {
log.error("合成图片异常");
e.printStackTrace();
}
}
public static void main(String[] args) {
MergeImg img = new MergeImg();
String path1 = "D:\\qrcode\\fee46d35ce2547adbded2475927df26f1561274933918.png";
String path2 = "D:\\qrcode\\timg.jpg";
String newPath = "D:\\qrcode\\mergeImg"+System.currentTimeMillis() + ".png";
img.saveMergeImage(path1,path2,newPath);
}
}
二、结果验证
图片:
三、说明
以上是基于最基本的实现方式,图片也是从网上随便下载的,这里只是一个入门参考,需要更高的要求还是好好设计一下,需要注意的就是合成图片的位置是由X轴和Y轴来决定的,他们的值就代表合成图片的左上角在被被合成图片中的位置。有其他问题欢迎交流。