Jdk1.8写一段生成二维码的程序
时间: 2024-03-06 18:35:48 浏览: 11
二维码生成程序
5星 · 资源好评率100%
可以使用 Java 的 java.awt.image 包中的 BufferedImage 类和 QRCodeWriter 类来编写一段生成二维码的程序。下面是一个示例:public static void main(String[] args) {
String qrCodeText = "Hello World";
int size = 125;
String fileType = "png";
File qrFile = new File("QRCode." + fileType);
createQRImage(qrFile, qrCodeText, size, fileType);
System.out.println("DONE!");
}private static void createQRImage(File qrFile, String qrCodeText, int size, String fileType) throws WriterException, IOException {
// Create the ByteMatrix for the QR-Code that encodes the given String
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
// Make the BufferedImage that are to hold the QRCode
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// Paint and save the image using the ByteMatrix
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, j, 1, 1);
}
}
}
ImageIO.write(image, fileType, qrFile);
}
阅读全文