Java — Generate QR Code using zxing | Code Factory

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
package com.example.java.programming;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
/**
* @author code.factory
*
*/
public class QRCodeGenerator {

private static final String IMAGE_PATH = "QR.png";
private static final String IMAGE_FORMAT = "PNG";

public static void main(String... args) {
try {
generateQR("Code Factory", 400, 400, IMAGE_PATH);
} catch(Exception e) {
e.printStackTrace();
}
}

private static void generateQR(String msg, int width, int height, String imagePath) throws WriterException, IOException {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = writer.encode(msg, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(imagePath);
MatrixToImageWriter.writeToPath(matrix, IMAGE_FORMAT, path);

/*If you want to return byte array of QR code then use below code*/
/*ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(matrix, IMAGE_FORMAT, pngOutputStream);
byte[] data = pngOutputStream.toByteArray();
return data;*/
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store