×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: digas
Added: Sep 26, 2014 3:23 PM
Views: 24
Tags: codes qr
  1. <dependency>
  2.      <groupId>com.google.zxing</groupId>
  3.      <artifactId>core</artifactId>
  4.      <version>1.6</version>
  5. </dependency>
  6. <dependency>
  7.      <groupId>com.google.zxing</groupId>
  8.      <artifactId>javase</artifactId>
  9.      <version>1.6</version>
  10. </dependency>
  11. Lets define an interface first. It is always a good idea to use interfaces when interacting with third-party components so that if you need to change the implementation altogether by using a different library, your change is isolated.
  12.  
  13.  
  14. package co.syntx.examples.qr;
  15.  
  16. import java.io.OutputStream;
  17.  
  18. public interface IQRService {
  19.  
  20.         /**
  21.          * Generate QR code of the specified content having the specified size.
  22.          * QRCode written to the output stream provided.
  23.          * @param size
  24.          * @param content
  25.          * @param outputStream
  26.          * @throws Exception
  27.          */
  28.         public abstract void generateQRCode(int width, int height, String content,
  29.                         OutputStream outputStream) throws Exception;
  30.  
  31. }
  32. Next, is the implementation of this interface.
  33.  
  34.  
  35. package co.syntx.examples.qr;
  36.  
  37. import java.io.OutputStream;
  38.  
  39.  
  40. import com.google.zxing.BarcodeFormat;
  41. import com.google.zxing.client.j2se.MatrixToImageWriter;
  42. import com.google.zxing.common.BitMatrix;
  43. import com.google.zxing.qrcode.QRCodeWriter;
  44.  
  45. public class QRService implements IQRService {
  46.  
  47.         private static final String IMAGE_FORMAT = "png";
  48.  
  49.         /* (non-Javadoc)
  50.          * @see co.syntx.examples.qr.IQRService#generateQRCode(java.lang.String, java.lang.String, java.io.OutputStream)
  51.          */
  52.         public void generateQRCode(int width, int height, String content, OutputStream outputStream) throws Exception {
  53.             String imageFormat = IMAGE_FORMAT;
  54.             BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE,width, height);
  55.             MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, outputStream);    
  56.         }
  57.  
  58. }