生成二维码的方法,基于zxing

时间:2023-03-08 18:47:05

现在生活中常用了一些二维码,这些在现实生活中已经非常密切了,那么怎么使用java来产生一个二维码呢?

下面给出代码

首先给出一个工具类,这里包含了生成二维码的图片对象,保存到流中,或者文件中:

package com.xiaojiezhu.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream; import javax.imageio.ImageIO; import com.google.zxing.common.BitMatrix; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} /**
* 把BitMatrix类中的对象,转换成一个二维码图片
* @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;
} /**
* 把二维码保存至文件
* @param matrix
* @param format
* @param file
* @throws IOException
*/
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} /**
* 把二维码保存至流对象
* @param matrix
* @param format
* @param stream
* @throws IOException
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
} }

下面给出使用的方法,基于上面的工具类:

public static void main(String[] args) {
try { //这个内容可以是网址,也可以是一段文字,如果是网址,就会跳转至此网址。如果是文字,就会直接显示文字内容
String content = "https://www.baidu.com";
//这个是保存的路径,当然,工具类中有一个重载的方法,也就是直接保存到流中,也就是一个outputstream
String path = "d:/"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map<EncodeHintType,String> hints = new HashMap<EncodeHintType,String>();
//设置编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//第一个参数是内容,或者网址,第二个参数是生成的类型,当前类型是二维码,也可以是条形码,后面是长度宽度,最后是声明的参数map
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
File file1 = new File(path,"餐巾纸.jpg");
//使用此方法保存至文件中
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
//使用此方法保存至输出流中
MatrixToImageWriter.writeToStream(bitMatrix, "jpg", new FileOutputStream("")); } catch (Exception e) {
e.printStackTrace();
}
}