java生成二维码带Logo
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.1.0</version>
</dependency>
工具类
package com.demo.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import java.util.UUID;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QrCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "jpg";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 100;
// LOGO高度
private static final int HEIGHT = 100;
/**
* 创建二维码图片
*
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
* @param filePath 生成的二维码图片的保存的路径
*/
public static void createQrCodeImage(String content, int qrCodeSize, String filePath) {
try {
BufferedImage bi = createQrCode(content, qrCodeSize);
File imgFile = new File(filePath);
ImageIO.write(bi, "JPEG", imgFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成包含字符串信息的二维码图片
*
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
*/
public static BufferedImage createQrCode(String content, int qrCodeSize) {
try {
// 设置二维码纠错级别Map
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
// 矫错级别
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
int matrixHeight = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 65, matrixWidth - 65, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixHeight);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i - 33, j - 33, 2, 2);
}
}
}
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QrCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二维码图片
* @param imgPath LOGO图片地址
* @param needCompress 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param imgPath LOGO地址
* @param destPath 存放目录
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath, boolean needCompress)
throws Exception {
BufferedImage image = QrCodeUtil.createImage(content, imgPath, needCompress);
mkdirs(destPath);
// 随机生成二维码图片文件名
String file = UUID.randomUUID() + ".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
return destPath + file;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
*
* @author lanyuan Email: mmm333zzz520@163.com
* @date 2013-12-11 上午10:16:36
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
}
/*
* 生成二维码
* http://192.168.124.8:8080/News/GoogleAPI
*/
@GetMapping(value="/GoogleAPI")
@ResponseBody
public static void main1(String[] args) throws Exception {
// 需要二维码携带的内容
//String content = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIzNDE5MDExNg==&scene=124#wechat_redirect";
String content = "乱码解决方法";
String newName=new String(content.getBytes(),"UTF-8");
// 生成二维码的大小
int qrCodeSize = 400;
// 将二维码保存的路径
//String filePath = "D:\\testQRImage.jpg";
// 将二维码保存的路径
String filePath = "C:\\Users\\chenlihong\\Desktop\\二维码.jpg";
// 执行工具类,生成二维码
QrCodeUtil.createQrCodeImage(newName, qrCodeSize, filePath);
System.out.println("二维码已生成");
}
/*
* 生成二维码
*
*/
@GetMapping(value="/GoogleAPI1")
@ResponseBody
public static void main(String[] args) throws Exception {
System.out.println("开始生成...");
//code();.
main3();
System.out.println("生成完毕!");
}
public static void code() {
try {
String content = "这个乱码吗";
String path = "C:\\Users\\chenlihong\\Desktop";// 二维码保存的路径
String codeName = UUID.randomUUID().toString();// 二维码的图片名
String imageType = "jpg";// 图片类型
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
File file1 = new File(path, codeName + "." + imageType);
MatrixToImageWriter.writeToFile(bitMatrix, imageType, file1);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void main3() throws Exception {
String text = "http://wx.imagingunion.com/iuweixin/iu_follow";
// String text = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIzNDE5MDExNg==&scene=124#wechat_redirect";
// String text ="https://tv.sohu.com/s/sohuplayer/iplay.html?bid=185350191&autoplay=true&disablePlaylist=true";
QrCodeUtil.encode(text,"C:\\Users\\chenlihong\\Desktop\\2.jpg","C:\\Users\\chenlihong\\Desktop",true);
//text是文字内容;"D:/MyWorkDoc/fangshou.jpeg"这是logo图片;"d:/MyWorkDoc"这是二维码保存的位置;true决定是否压缩。
}