该方法参考https://www.jianshu.com/p/7ae3b7002530该作者。详细请点该链接。获取的jar包在该作者下可免费获取
导入jar包(zxing-code-2.3.jar)
一。工具类一,直接调用该工具类生成带logo的二维码,(可带文字)
package com.javajy.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.apache.commons.lang.StringUtils;
import com.google.gson.Gson;
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 Administrator
*
*/
public class QRCodeFactory {
//FileUploadUtil.host:访问地址“http://192.168.1.100/”
private static final int BLACK = 0xFF000000;//用于设置图案的颜色
private static final int WHITE = 0xFFFFFFFF; //用于背景色
public static String FORMAT = "png";//图片格式
private static int WIDTH =500;//定义二维码宽
private static int HEIGHT =500;//定义二维码长
private static int fontSize = 19; //字体大小
private static int fontStyle = 7; //字体风格
/*
二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的
生产条形码的基类
*/
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图片
*/
// URL imageResource = this.getClass().getResource(logUri);
File file = new File(logUri);
BufferedImage logo = ImageIO.read(file);
//开始绘制图片
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 String CreatQrImage(String content,String outFileUri,String logUri,String text,String name) throws IOException, WriterException{
// 2.
Hashtable
// 指定纠错等级,纠错级别(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());
String path = this.writeToFile(bitMatrix, FORMAT, outFileUri, outputFile,logUri,text,name);//调用的生成二维码图片方法
return path;
}
/**
* 生成二维码图片
* @param matrix
* @param format
* @param file 指定生成的文件
* @param logUri 二维码中间logo的地址
* @throws IOException
*/
public static String writeToFile(BitMatrix matrix, String format, String outFileUri,File file,String logUri,String text,String name) 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());
if(StringUtils.isNotBlank(text)){
//带文字生产文件
path =pressText(text, file.getPath(), outFileUri, fontStyle, Color.BLACK, fontSize, WIDTH, HEIGHT,name);
}else{
//不带文字
path = FileUploadUtil.host+file.getPath().substring(file.getPath().lastIndexOf("\\")+1);//此处为访问的路径
}
return path;//返回二维码图片路径
}
}
/**
* @为图片添加文字
* @param text 文字
* @param outFileUri 带文字的图片地址
* @param logoimage 需要添加文字的图片
* @param fontStyle
* @param color
* @param fontSize
* @param width
* @param heigh
*/
public static String pressText(String text, String logoimage,String outFileUri,int fontStyle,
Color color, int fontSize, int width, int height,String name) {
String path ="";
//计算文字开始的位置
//x开始的位置:(图片宽度-字体大小*字的个数)/2
int startX = width/2-text.length()*6;
//y开始的位置:图片高度-(图片高度-图片宽度)/2
int startY = height-(height-width)/2-fontSize/2;
try {
File file = new File(logoimage);
Image src = ImageIO.read(file);
int imageW = src.getWidth(null);
int imageH = src.getHeight(null);
BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, imageW, imageH, null);
g.setColor(color);
g.setFont(new Font(null, fontStyle, fontSize));
g.drawString(text, startX, startY);
g.dispose();
FileOutputStream out = new FileOutputStream(outFileUri);
path = FileUploadUtil.host+name;
ImageIO.write(image, FORMAT, out);
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// encoder.encode(image);
out.close();
System.out.println("image press success!!文字二维码地址:"+path);
} catch (Exception e) {
System.out.println(e);
}
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 = "***";//页面链接/内容
//必须是同一服务器的图片路径
String logUri = "";logo图片
System.out.println(logUri);
String name = new Date().getTime()+".png";//自定义二维码图片名
String outFileUri="D:\\workspace/lianbei/src/main/webapp/lianben-admin/img/"+name;//自定义二维码访问路径
String text="QAZ";//需要添加的文字
System.out.println(text.length());
QRCodeFactory qf = new QRCodeFactory();
try {
String path = qf.CreatQrImage(content,outFileUri, logUri,text,name);//创建我们的二维码图片
} 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
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();
}
}
}