Skip to content

Instantly share code, notes, and snippets.

@drewdev02
Created May 3, 2023 05:08
Show Gist options
  • Save drewdev02/74767475b314df806db71ac258870ba2 to your computer and use it in GitHub Desktop.
Save drewdev02/74767475b314df806db71ac258870ba2 to your computer and use it in GitHub Desktop.
package src;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
public class QRCodeGenerator {
public static void main(String[] args) throws WriterException, IOException {
var qrCodeData = "hola";
var filePath = "qr.png";
var size = 250;
var fileType = "png";
var qrFile = new File(filePath);
var hintMap = new HashMap<EncodeHintType, Object>();
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
var qrCodeWriter = new QRCodeWriter();
var byteMatrix = qrCodeWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, size, size, hintMap);
var matrixWidth = byteMatrix.getWidth();
var image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
var graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment