In this article, we will look at how to use the Zxing QR code generation library and JFreeSVG library to create a QR Code SVG image in Java.
QR Code Generation
The below code creates a object representing QR Code using Zxing library:java.awt.image.BufferedImage
1 | public static BufferedImage getQRCode(String targetUrl, int width, int height) { try { Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix byteMatrix = qrCodeWriter.encode(targetUrl, BarcodeFormat.QR_CODE, width, height, hintMap); int CrunchifyWidth = byteMatrix.getWidth(); BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth); graphics.setColor(Color.BLACK); for (int i = 0; i < CrunchifyWidth; i++) { for (int j = 0; j < CrunchifyWidth; j++) { if (byteMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } return image; } catch (WriterException e) { e.printStackTrace(); throw new RuntimeException("Error getting QR Code"); } } |
Conversion to SVG
The below code snippet converts the object into SVG using JFreeSVG:java.awt.image.BufferedImage
1 | public static String getQRCodeSvg(String targetUrl, int width, int height, boolean withViewBox){ SVGGraphics2D g2 = new SVGGraphics2D(width, height); BufferedImage qrCodeImage = getQRCode(targetUrl, width, height); g2.drawImage(qrCodeImage, 0,0, width, height, null); ViewBox viewBox = null; if ( withViewBox ){ viewBox = new ViewBox(0,0,width,height); } return g2.getSVGElement(null, true, viewBox, null, null); } |
The complete code can be found here.
Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: How to create a QR Code SVG using Zxing and JFreeSVG in Java? Opinions expressed by Java Code Geeks contributors are their own. |
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Thank you!
We will contact you soon.
👁 Photo of Mohamed Sanaulla
Mohamed SanaullaApril 21st, 2019Last Updated: April 18th, 2019
Mohamed SanaullaApril 21st, 2019Last Updated: April 18th, 2019
0 335 1 minute read

This site uses Akismet to reduce spam. Learn how your comment data is processed.