java生成二维码图片方法如下:
/**
* 绘制二维码
* @param contents 二维码内容
* @return image 二维码图片
* */
private static BufferedImage encodeImg(String contents){
BufferedImage image = null;
try{
BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
int width = matrix.getWidth();
int height = matrix.getHeight();
for(int x = 0; x < width; x++){
for(int y =0;y < height; y++){
image.setRGB(x, y, matrix.get(x, y) && y <= width ? BLACK : WHITE);
}
}
}catch(Exception e){
logger.error("生成二维码失败", e);
}
return image;
}
以上是单独生成一个二维码图片。这里的参数contents是指扫描二维码后进行的操作一般指具体跳转页面的地址。
如果还需要在二维码中加入logo标志。则需要利用已经生成的无图片的二维码将logo进行生成。
在二维码中生成logo代码:
/**
* 二维码绘制logo
* @param logoImg logo图片文件
* @param qrCode 二维码文件
* @param title 标题
* */
private static BufferedImage encodeImgLogo(File logoImg, BufferedImage qrCode, String title){
BufferedImage newImage = null;
try{
int w = qrCode.getWidth();
int h = qrCode.getHeight();
//开始合并绘制图片
newImage = new BufferedImage(WIDTH, HEIGHT + 80, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D)newImage.getGraphics();
g2.drawImage(qrCode, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
BufferedImage logo = null;
if(logoImg.exists() && logoImg.isFile()){
//读取logo图片
logo = ImageIO.read(logoImg);
//设置二维码大小,太大,会覆盖二维码,此处20%
int lw = logo.getWidth() > w * 2 /10 ? (w * 2 /10) : logo.getWidth();
int lh = logo.getHeight() > h * 2 /10 ? (h * 2 /10) : logo.getHeight();
//设置logo图片放置位置
//中心
int x = (w - lw) / 2;
int y = (h - lh) / 2;
g2.drawImage(logo, x, y, lw, lh, null);
}
//有宽500高80的黑色块,用白线覆盖
for(int i = HEIGHT; i < HEIGHT + 80; i++){
g2.drawLine(0, i, WIDTH, i);
}
//写入商户名称
drawString(g2, title, w, h + 30);
g2.dispose();
qrCode.flush();
if(null != logo) {
logo.flush();
}
newImage.flush();
}catch(Exception e){
logger.error("二维码绘制logo失败:{}", e);
}
return newImage;
}
以上就是利用java生成二维码功能