java怎么生成二维码
时间: 2023-05-12 18:07:08 浏览: 135
java 生成二维码
4星 · 用户满意度95%
Java可以使用第三方库zxing来生成二维码,具体实现可以参考以下代码:
```java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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;
public class QRCodeGenerator {
private static final String QR_CODE_IMAGE_PATH = "./MyQRCode.png";
private static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int grayValue = (bitMatrix.get(x, y) ? 0 : 1) & 0xff;
bufferedImage.setRGB(x, y, (grayValue == 0 ? 0 : 0xFFFFFF));
}
}
File qrCodeImage = new File(filePath);
ImageIO.write(bufferedImage, "png", qrCodeImage);
}
public static void main(String[] args) {
try {
generateQRCodeImage("https://www.baidu.com", 350, 350, QR_CODE_IMAGE_PATH);
System.out.println("二维码生成成功!");
} catch (WriterException e) {
System.out.println("二维码生成失败,WriterException :: " + e.getMessage());
} catch (IOException e) {
System.out.println("二维码生成失败,IOException :: " + e.getMessage());
}
}
}
```
阅读全文