|
| 1 | +import java.io.File; |
| 2 | +import java.io.IOException; |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import com.google.zxing.BarcodeFormat; |
| 7 | +import com.google.zxing.EncodeHintType; |
| 8 | +import com.google.zxing.MultiFormatWriter; |
| 9 | +import com.google.zxing.Writer; |
| 10 | +import com.google.zxing.WriterException; |
| 11 | +import com.google.zxing.common.BitMatrix; |
| 12 | +import com.google.zxing.qrcode.QRCodeWriter; |
| 13 | +import com.google.zxing.client.j2se.MatrixToImageWriter; |
| 14 | +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; |
| 15 | + |
| 16 | +public class QRCodeGenerator { |
| 17 | + public static void main(String[] args) { |
| 18 | + // The data to be encoded as a QR code |
| 19 | + String data = "Hello, this is a QR code example!"; |
| 20 | + |
| 21 | + // Path where the QR code image will be saved |
| 22 | + String filePath = "qrcode.png"; |
| 23 | + |
| 24 | + // Encoding charset |
| 25 | + String charset = "UTF-8"; |
| 26 | + |
| 27 | + // Create a QR code writer |
| 28 | + QRCodeWriter writer = new QRCodeWriter(); |
| 29 | + |
| 30 | + // Set QR code parameters |
| 31 | + Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<>(); |
| 32 | + hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); |
| 33 | + |
| 34 | + try { |
| 35 | + // Generate a QR code |
| 36 | + BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, 200, 200, hintMap); |
| 37 | + |
| 38 | + // Save the QR code as an image |
| 39 | + MatrixToImageWriter.writeToFile(bitMatrix, "PNG", new File(filePath)); |
| 40 | + |
| 41 | + System.out.println("QR Code generated and saved as " + filePath); |
| 42 | + } catch (WriterException | IOException e) { |
| 43 | + e.printStackTrace(); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments