该方法参考https://www.jianshu.com/p/7ae3b7002530该作者。详细请点该链接。获取的jar包在该作者下可免费获取
一。工具类一,直接调用该工具类生成带logo的二维码(两个类整合为一个工具类)
package com.javajy.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 本类用于对我们二维码进行参数的设定,生成我们的二维码:
* @author kingwen
*/
/**
* @author Administrator
*
*/
public class QRCodeFactory {
public static String host ="http://****";//服务器访问IP
public static String rootPath= "D:\\*****/img/";//服务器访问路径
private static final int BLACK = 0xFF000000;//用于设置图案的颜色
private static final int WHITE = 0xFFFFFFFF; //用于背景色
/*
二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的
生产条形码的基类
*/
// private MatrixToImageWriter() {
// }
//
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, (matrix.get(x, y) ? BLACK : WHITE));
// image.setRGB(x, y, (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
}
}
return image;
}
/**
* 给生成的二维码添加中间的logo
* @param matrixImage 生成的二维码
* @param logUri logo地址
* @return 带有logo的二维码
* @throws IOException logo地址找不到会有io异常
*/
public BufferedImage setMatrixLogo(BufferedImage matrixImage,String logUri) throws IOException{
/**
* 读取二维码图片,并构建绘图对象
*/
Graphics2D g2 = matrixImage.createGraphics();
int matrixWidth = matrixImage.getWidth();
int matrixHeigh = matrixImage.getHeight();
/**
* 读取Logo图片
*/
BufferedImage logo = ImageIO.read(new File(logUri));
//开始绘制图片
g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);
//绘制边框
BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
// 设置笔画对象
g2.setStroke(stroke);
//指定弧度的圆角矩形
RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
g2.setColor(Color.white);
// 绘制圆弧矩形
g2.draw(round);
//设置logo 有一道灰色边框
BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
// 设置笔画对象
g2.setStroke(stroke2);
RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
g2.setColor(new Color(128,128,128));
g2.draw(round2);// 绘制圆弧矩形
g2.dispose();
matrixImage.flush() ;
return matrixImage ;
}
/**
* 创建我们的二维码图片
* @param content 二维码内容
* @param format 生成二维码的格式
* @param outFileUri 二维码的生成地址
* @param logUri 二维码中间logo的地址
* @param size 用于设定图片大小(可变参数,宽,高)
* @throws IOException 抛出io异常
* @throws WriterException 抛出书写异常
*/
public void CreatQrImage(String content,String format,String outFileUri,String logUri, int[] size) throws IOException, WriterException{
//1.
int width = 200; // 二维码图片宽度 430
int height = 200; // 二维码图片高度430
//如果存储大小的不为空,那么对我们图片的大小进行设定
if(size.length==2){
width=size[0];
height=size[1];
}else if(size.length==1){
width=height=size[0];
}
// 2.
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 内容所使用字符集编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
//hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,//要编码的内容
//编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
//Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
//MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
BarcodeFormat.QR_CODE,
width, //条形码的宽度
height, //条形码的高度
hints);//生成条形码时的一些配置,此项可选
// 指定生成二维码图片文件
File outputFile = new File(outFileUri);
// //指定输出路径
// System.out.println("输出文件路径为"+outputFile.getPath());
this.writeToFile(bitMatrix, format, outputFile,logUri);//调用的生成二维码图片方法
}
/**
* 生成二维码图片
* @param matrix
* @param format
* @param file
* @param logUri 二维码中间logo的地址
* @throws IOException
*/
public static String writeToFile(BitMatrix matrix, String format, File file,String logUri) throws IOException {
String path="";
System.out.println("write to file");
BufferedImage image = toBufferedImage(matrix);
//设置logo图标
QRCodeFactory logoConfig = new QRCodeFactory();
image = logoConfig.setMatrixLogo(image, logUri);
if (!ImageIO.write(image, format, file)) {
System.out.println("生成图片失败");
throw new IOException("Could not write an image of format " + format + " to " + file);
}else{
System.out.println("图片生成成功!"+file.getPath());
path = file.getPath();
return path;//返回二维码图片路径
}
}
/**
* 生成二维码图片流
* @param matrix
* @param format
* @param stream
* @param logUri
* @throws IOException
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream,String logUri) throws IOException {
BufferedImage image = toBufferedImage(matrix);
//设置logo图标
QRCodeFactory logoConfig = new QRCodeFactory();
image = logoConfig.setMatrixLogo(image, logUri);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
public static void main(String[] args) {
String content="http://****";//页面链接
String logUri=rootPath+"Starry.jpg";//logo文件(自测的时候传本地图片路径)
String outFileUri="D:/"+new Date().getTime()+".png";//二维码访问路径
int[] size=new int[]{200,200};
String format = "png";
QRCodeFactory qf = new QRCodeFactory();
try {
qf.CreatQrImage(content, format, outFileUri, logUri, size);//创建我们的二维码图片
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
}
}
二。工具类二,可直接调用,该工具logo不带边距
package com.javajy.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.imageio.ImageIO;
import org.apache.commons.lang.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 画制定logo和制定描述的二维码
*
* @author songyz
*
*/
public class QrCodeUtil {
private static final int QRCOLOR = 0xFF000000; // 默认是黑色
private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
private static final int WIDTH = 400; // 二维码宽
private static final int HEIGHT = 400; // 二维码高
// 用于设置QR二维码参数
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
put(EncodeHintType.MARGIN, 0);
}
};
public static void main(String[] args) throws WriterException {
File logoFile = new File("D:/img/Starry.jpg");//logo文件
File QrCodeFile = new File("D:/"+new Date().getTime()+".png");//二维码访问路径
String url = "http://*****";//页面链接
String note = "";//备注
drawLogoQRCode(logoFile, QrCodeFile, url, note);
}
// 生成带logo的二维码图片
public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
}
}
int width = image.getWidth();
int height = image.getHeight();
if (Objects.nonNull(logoFile) && logoFile.exists()) {
// 构建绘图对象
Graphics2D g = image.createGraphics();
// 读取Logo图片
BufferedImage logo = ImageIO.read(logoFile);
// 开始绘制logo图片
g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
g.dispose();
logo.flush();
}
// 自定义文本描述
if (StringUtils.isNotEmpty(note)) {
// 新的图片,把带logo的二维码下面加上文字
BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D outg = outImage.createGraphics();
// 画二维码到新的面板
outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
outg.setColor(Color.BLACK);
outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
int strWidth = outg.getFontMetrics().stringWidth(note);
if (strWidth > 399) {
// //长度过长就截取前面部分
// 长度过长就换行
String note1 = note.substring(0, note.length() / 2);
String note2 = note.substring(note.length() / 2, note.length());
int strWidth1 = outg.getFontMetrics().stringWidth(note1);
int strWidth2 = outg.getFontMetrics().stringWidth(note2);
outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D outg2 = outImage2.createGraphics();
outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
outg2.setColor(Color.BLACK);
outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
outg2.dispose();
outImage2.flush();
outImage = outImage2;
} else {
outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
}
outg.dispose();
outImage.flush();
image = outImage;
}
image.flush();
ImageIO.write(image, "png", codeFile); // TODO
} catch (Exception e) {
e.printStackTrace();
}
}
}