Java生成二维码
时间: 2023-07-09 18:14:46 浏览: 179
Java 生成二维码
要在Java中生成二维码,可以使用ZXing库。下面是一段示例代码,可以将一个字符串生成为二维码图片:
```java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRCodeWriter {
public static void main(String[] args) {
try {
String text = "Hello, world!";
int width = 200;
int height = 200;
String format = "png";
String filePath = "qrcode.png";
// set QR code parameters
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
// create the BufferedImage object
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
// set white background
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
// set QR code colors
graphics.setColor(Color.BLACK);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (bitMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
// save QR code image to file
File qrCodeImage = new File(filePath);
ImageIO.write(image, format, qrCodeImage);
System.out.println("QR Code generation completed!");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码会将字符串"Hello, world!"生成为一个200x200像素的二维码图片,并保存到文件"qrcode.png"中。注意需要导入ZXing库及其依赖。
阅读全文