开发语言:这里使用的是java
具体思路:这个大家应该都知道,先把头像放到二维码上,生成带头像的二维码图片,然后再把带头像的二维码图片添加到海报图片上
具体代码实现如下:(效果如何需要自己亲自实践啦)
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.net.URL;
public class AddPic {
public static void main(String[] args)throws IOException {
String userPath ="头像的url";
String qrcodeImg ="二维码的url";
String posterPath ="海报url";
BufferedImage qrcodeImage1 = ImageIO.read(new URL(qrcodeImg));
//获取海报图片
BufferedImage posterImage = ImageIO.read(new URL(posterPath));
Graphics posterGrap = posterImage.getGraphics();
BufferedImage userImage = ImageIO.read(new URL(userPath));
System.out.println("Add icon to the qrcode!");
String headImgPath ="xxxxxxxxxxxxxxxxxxxxxxxxx";
BufferedImage qrcodeImage =new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB),null).filter(qrcodeImage1,null);
Graphics qrcodeGrap = qrcodeImage.getGraphics();
qrcodeGrap.drawImage(userImage, qrcodeImage.getWidth()/8*3, qrcodeImage.getHeight()/8*3, qrcodeImage.getWidth()/4, qrcodeImage.getHeight()/4,null);
File qrcodeFile =new File(headImgPath);
ImageIO.write(qrcodeImage,"PNG", qrcodeFile);
InputStream imagein =new FileInputStream(headImgPath);
BufferedImage headQrcodeImage = ImageIO.read(imagein);
posterGrap.drawImage(headQrcodeImage,0,0, Integer.parseInt("100"), Integer.parseInt("100"),null);
String finalPosterPath ="合成的图片";
File posterFile =new File(finalPosterPath);
OutputStream out =new FileOutputStream(posterFile);
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(out);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()){
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.2f);
}
writer.write(null,new IIOImage(posterImage,null,null), param);
out.close();
ios.close();
writer.dispose();
}
}
需要注意的问题:
1、图片的色彩空间,例如微信生成的二维码默认的色彩空间是什么,因为我们希望生成头像二维码上是彩色的头像,对吧
2、生成的图片太大,不利于传输,那么就要考虑图片压缩
3、一张图片添加到另一张图片上时,位置的设置
4、图片合成的执行速度相对较慢,要用专门的线程处理