Java 二维码QRCode生成与解析
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
public class QRCodeGenerator {
public static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
File file = new File(filePath);
ImageIO.write(toBufferedImage(bitMatrix), "png", file);
}
private 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) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
public static void main(String[] args) {
try {
generateQRCodeImage("Hello, World!", 350, 350, "hello_world.png");
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
}
这段代码使用了com.google.zxing
库来生成一个包含文本 "Hello, World!" 的二维码图片,并将其保存为PNG格式的文件。generateQRCodeImage
方法接受文本、宽度、高度和文件路径作为参数,使用QRCodeWriter
类生成二维码,并使用ImageIO.write
将其输出为图片。在主方法中,我们调用generateQRCodeImage
方法生成一个二维码图片。
评论已关闭