java代码url生成二维码图片
时间: 2023-09-09 15:07:26 浏览: 86
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.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QrCodeGenerator {
public static void main(String[] args) throws WriterException, IOException {
String url = "https://www.example.com";
int width = 300;
int height = 300;
String format = "png";
File qrFile = new File("qrcode.png");
Map<EncodeHintType, Object> hintMap = new HashMap<EncodeHintType, Object>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
createQRCode(url, width, height, format, hintMap, qrFile);
}
private static void createQRCode(String url, int width, int height, String format, Map hintMap, File qrFile)
throws WriterException, IOException {
BitMatrix matrix = new MultiFormatWriter().encode(new String(url.getBytes("UTF-8"), "ISO-8859-1"),
BarcodeFormat.QR_CODE, width, height, hintMap);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
java.awt.Graphics2D graphics = (java.awt.Graphics2D) image.getGraphics();
graphics.setColor(java.awt.Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setColor(java.awt.Color.BLACK);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (matrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
ImageIO.write(image, format, qrFile);
}
}
```
该代码可以生成一个指定URL的二维码图片,保存在本地文件qrcode.png中。
阅读全文