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;*/
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Calculate Average Lambda Cold Start Times

Top 5 Free Visual Studio Extensions for Web Development | iFour Technolab

Top 5 Free Visual Studio Extensions for Web Development | iFour Technolab

Oracle Cloud Serverless Functions unleashed: exposing OCI Functions through API Gateway

Fast Node Sync with Tezos Tarballs

ETL Best Practice

I am learning both front and backend software development with zuri @ https://internship.zuri.team.

Down with the Krew — my favourite kubectl plugins

Privilege Escalation in AKS Clusters

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
Code Factory

Code Factory

More from Medium

import Json dependency in JAVA

Visitor Design Pattern in Java

Java — Version Evolution

Java Packages & API-10 example