Created
June 30, 2019 02:35
-
-
Save jalispran/b3a6ab653e4d52981ffe412dd70b4b18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private byte[] generateQrImage(String content) throws WriterException, IOException { | |
// Create new configuration that specifies the error correction | |
Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>(); | |
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); | |
// Create a qr code with the url as content and a size of WxH px | |
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints); | |
// Load QR image | |
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix, new MatrixToImageConfig(BLACK, WHITE)); | |
// Load logo image | |
BufferedImage overly = getOverly(LOGO); | |
// Calculate the delta height and width between QR code and logo | |
int deltaHeight = qrImage.getHeight() - overly.getHeight(); | |
int deltaWidth = qrImage.getWidth() - overly.getWidth(); | |
// Initialize combined image | |
BufferedImage combined = new BufferedImage(qrImage.getHeight(), qrImage.getWidth(), BufferedImage.TYPE_INT_ARGB); | |
Graphics2D g = (Graphics2D) combined.getGraphics(); | |
// Write QR code to new image at position 0/0 | |
g.drawImage(qrImage, 0, 0, null); | |
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); | |
// Write logo into combine image at position (deltaWidth / 2) and | |
// (deltaHeight / 2). Background: Left/Right and Top/Bottom must be | |
// the same space for the logo to be centered | |
g.drawImage(overly, deltaWidth/2, deltaHeight/2, null); | |
g.dispose(); | |
// Write combined image as PNG to OutputStream | |
ByteArrayOutputStream os = new ByteArrayOutputStream(); | |
ImageIO.write(combined, "png", os); | |
os.toByteArray(); | |
os.close(); | |
return os.toByteArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment