forked from 790hanu/Annex-qr-code-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateQRCode.java
59 lines (50 loc) · 2 KB
/
GenerateQRCode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.journaldev.qrcode.generator;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
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 GenerateQRCode {
public static void main(String[] args) throws WriterException, IOException {
String qrCodeText = "https://www.journaldev.com";
String filePath = "JD.png";
int size = 125;
String fileType = "png";
File qrFile = new File(filePath);
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<>();
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);
}
}