准备工作
1.需要依赖zxing的jar包 jar下载,或者maven依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
2.zXing是开源项目,地址:github
3.通用方法,这个方法是生成普通二维码,并且背景是黑白色
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 java.awt.image.BufferedImage;
/**
*创建背景色为黑白色的二维码
* @param url 二维码内容
* @param charset 二维码内容字符集
* @param hint 二维码参数设定
* @param width 二维码宽度
* @param height 二维码高度
* @return
* @author h
*/
public static BufferedImage createQRCode(String url, String charset, Map<EncodeHintType, ?> hint, int width,
int height) {
BitMatrix matrix;
try {
matrix = new MultiFormatWriter().encode(new String(url.getBytes(charset), charset), BarcodeFormat.QR_CODE,
width, height, hint);
return toBufferedImage(matrix);
} catch (WriterException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* toBufferedImage
*修改图片背景色
* @param matrix
* @return
*/
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);
}
}
return image;
}
一、生成普通二维码
1.1生成普通二维码
/**
*创建普通二维码,字符为utf-8
* @param url
* @return
* @author h
*/
public static BufferedImage createQRCode(String url) {
//二维码配置
Map hint = new HashMap();
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//容错级别,共4级,详细百度
hint.put(EncodeHintType.CHARACTER_SET, QRCODE_CHARSET);//字符集
hint.put(EncodeHintType.MARGIN, 2);//二维码外边距
return createQRCode(url, QRCODE_CHARSET, hint, QRCODE_WIDTH, QRCODE_HEIGHT);
}
1.2低版本包二维码去除白边
这里使用3.3,使用键值对EncodeHintType.MARGIN值为0时即可去除白边
/**
* 删除白边,低版本使用
*/
private static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}
二、生成logo二维码
/**
* Create qrcode with default settings and logo
*中间带logo的二维码
* @param data 二维码内容
* @param logoFile logo图片路径
* @return
* @author h
*/
@SuppressWarnings("unchecked")
public static BufferedImage createQRCodeWithLogo(String data, File logoFile) {
Map hint = new HashMap();
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//容错级别,共4级,详细百度
hint.put(EncodeHintType.CHARACTER_SET, QRCODE_CHARSET);//字符集编码
hint.put(EncodeHintType.MARGIN, 0);//二维码外边距
return createQRCodeWithLogo(data, QRCODE_CHARSET, hint, QRCODE_WIDTH, QRCODE_HEIGHT, logoFile);
}
/**
* Create qrcode with specified hint and logo
*
* @param url 二维码内容
* @param charset 字符集 默认UTF-8
* @param hint 二维码配置
* @param width 宽
* @param height 高
* @param logoFile logo文件
* @return
* @author h
*/
public static BufferedImage createQRCodeWithLogo(String url, String charset, Map<EncodeHintType, ?> hint,
int width, int height, File logoFile) {
try {
BufferedImage qrcode = createQRCode(url, charset, hint, width, height);
BufferedImage logo = ImageIO.read(logoFile);
BufferedImage combined = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) combined.getGraphics();
//设置二维码大小,太大,会覆盖二维码,此处20%
int logoWidth = logo.getWidth() > qrcode.getWidth() * 2 / 10 ? (qrcode.getWidth() * 2 / 10) : logo.getWidth();
int logoHeight = logo.getHeight() > qrcode.getHeight() * 2 / 10 ? (qrcode.getHeight() * 2 / 10) : logo.getHeight();
//设置logo图片放置位置--中心
int x = Math.round((qrcode.getWidth() - logoWidth) / 2);
int y = Math.round((qrcode.getHeight() - logoHeight) / 2);
g.drawImage(qrcode, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
//开始合并绘制图片
g.drawImage(logo, x, y, logoWidth, logoHeight, null);
g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
//logo边框大小
g.setStroke(new BasicStroke(3));
//logo边框颜色
g.setColor(Color.white);
g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
g.dispose();
logo.flush();
qrcode.flush();
return combined;
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
三、生成条形码
条形码生成是有一定规则的,这里使用的是CODE_128,该条码包括大写字母、数字、常用标点符号和一些控制符。这里给个参考:
条形码使用规则
/**
* 条形码
*
* @param contents 内容
* @param width 宽
* @param height 高
* @param imgPath 生成后文件路径
*/
public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
+ // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
File file = new File(imgPath);
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,BarcodeFormat.CODE_128, codeWidth, height, null);
MatrixToImageWriter.writeToPath(bitMatrix, "png", file.toPath());
} catch (Exception e) {
e.printStackTrace();
}
}
测试
main方法测试+图片
//字符集
public static final String QRCODE_CHARSET = "UTF-8";
//高度
public static final int QRCODE_HEIGHT = 300;
//宽度
public static final int QRCODE_WIDTH = 300;
//黑
private static final int BLACK = 0xFF000000;
//白
private static final int WHITE = 0xFFFFFFFF;
public static void main(String[] args) throws IOException, NotFoundException {
//生成普通二维码
BufferedImage qrCode = createQRCode("https://www.baidu.com/");
ImageIO.write(qrCode, "png", new File("D:/普通二维码.png"));
//生成logo二维码
String data = "https://www.baidu.com/";
File logoFile = new File("D:/1234.png");
BufferedImage image = QrTest2.createQRCodeWithLogo(data,logoFile);
ImageIO.write(image, "png", new File("D:/logo二维码.png"));
//生成条形码
String imgPath = "D:/条码.png";
String contents = "6926557300360";
int width = 400, height = 100;
encode(contents, width, height, imgPath);
System.out.println("结束");
}
去除白边的logo二维码
条码
普通二维码