Java implements a QR code with logo
QR code applied to all aspects of life, will use code to implement the QR code, I think it must be a bonus skill. All right, let's make it work together.
The QR code that we implement is based on the standard of the code, QR code is a matrix two-dimensional code symbol number developed by Nippon Denso Corporation in 1994, the name is quick Response code
QR Code: Patent open, support Chinese;
Compared with other two-dimensional code, QR code has the advantages of fast reading speed, large data density and small occupied space.
Error correction Ability:
L-level: about 7% of the data code Word can be corrected
M-class: approx. 15% Data code Word Error
Q-level: About 25% of the data code Word can be corrected
H-Class: About 30% of the data code Word can be corrected
After knowing these hard knowledge, we do the preparatory work, we need to download two jar packages, assist us to develop, here I put the link
Http://mavenrepository.com/artifact/com.google.zxing/javase
http://mavenrepository.com/artifact/com.google.zxing/core/3.3.2
We are in our project, a new Java Project project will be able to create a new three lib, Utils, test three folders, lib storage jar, Utils let us write the tool class, test to let us write the testing class
We start with the two-dimensional code of the logo never begin thinking:
1, set some QR code parameters, such as Character set, margin, fault tolerance level
2, generate two-dimensional code
All right, let's make it come true.
/** * * @param width QR code wide * * @param height Two-dimensional code high * * @param content two-dimensional code * */public static void Createqrcode (int width, int height, String content) {//1, set QR code Some parameters of HashMap hints = new HashMap (); 1.1 Set the character set Hints.put (Encodehinttype.character_set, "utf-8"); 1.2 Set the level of fault tolerance, because of the fault tolerance, within a certain range can be the QR code p into your favorite style hints.put (Encodehinttype.error_correction, ERRORCORRECTIONLEVEL.M); 1.3 set margin, (i.e. white area) Hints.put (Encodehinttype.margin, 1); 2. Generate QR Code try {//2.1 define Bitmatrix object Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (Con Tent, Barcodeformat.qr_code, width, height, hints); 2.2, set the two-dimensional code storage path, and QR code name path Codepath = new File ("c:/users/admin/desktop/code/" + uuid.randomuuid () + ". png") . Topath (); 2.3, the implementation of the generation of two-dimensional code matrixtoimagewriter.writetopath (Bitmatrix, "PNG", Codepath); } catch (ExcEption e) {//TODO auto-generated catch block E.printstacktrace (); } }
Let's realize the two-dimensional code idea with logo:
1, our husband into a Logoconfig configuration class, mainly set the logo border color; logo border width; logo size
2, set some two-dimensional code parameters
3, generate two-dimensional code
4. Create two-dimensional code with logo
Let's make it come true.
Logoconfig class
class LogoConfig { // logo默认边框颜色 public static final Color DEFAULT_BORDERCOLOR = Color.WHITE; // logo默认边框宽度 public static final int DEFAULT_BORDER = 2; // logo大小默认为照片的1/6 public static final int DEFAULT_LOGOPART = 6; private final int border = DEFAULT_BORDER; private final Color borderColor; private final int logoPart; public LogoConfig() { this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART); } public LogoConfig(Color borderColor, int logoPart) { this.borderColor = borderColor; this.logoPart = logoPart; } public Color getBorderColor() { return borderColor; } public int getBorder() { return border; } public int getLogoPart() { return logoPart; }}
Tool function to generate two-dimensional code with logo in middle
/** * Generate a logo in the middle of the QR code * * @param width * @param height * @param content */public static void CR Eatelogoqrcode (int width, int height, String content) {///1, set some parameters of the QR code HashMap hints = new HashMap (); 1.1 Set the character set Hints.put (Encodehinttype.character_set, "utf-8"); 1.2 Set the level of fault tolerance, because of the fault tolerance, within a certain range can be the QR code p into your favorite style hints.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H); 1.3 set margin, (i.e. white area) Hints.put (Encodehinttype.margin, 1); 2. Generate QR Code try {//2.1 define Bitmatrix object Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (Con Tent, Barcodeformat.qr_code, width, height, hints); 2.2, set the two-dimensional code storage path, and the name of the two-dimensional code//Qrfile used to store the generated QR code image file Qrfile = new file ("C:/users/admin/desktop/code" , Uuid.randomuuid () + ". jpg"); Logofile is used to store a QR code image with a logo file Logofile = new file ("C:/users/admin/desktop/code", "test.jpg"); 2.3, the implementation of the generation of two-dimensional code Matrixtoimagewriter.writetopath (Bitmatrix, "JPG", Qrfile.topath ()); 2.4 Add logo to QR code logoconfig logoconfig = new Logoconfig (); Addlogo (Qrfile, Logofile, logoconfig); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } }
Tool class for adding logos
/** * * @param qrpic QR code file path * @param logopic logo file path * @param logoconfig Configuration class */private static V OID Addlogo (file qrpic, file Logopic, Logoconfig logoconfig) {if (!qrpic.isfile () | | |!logopic.isfile ()) { SYSTEM.OUT.PRINTLN ("File not found!"); System.exit (0); try {//1, read the QR code picture, and build the drawing object bufferedimage image = Imageio.read (qrpic); Graphics2D graph = image.creategraphics (); 2, read the logo image BufferedImage logo = Imageio.read (logopic); int widthlogo = Image.getwidth ()/Logoconfig.getlogopart (); int heightlogo = Image.getheight ()/Logoconfig.getlogopart (); 3, calculate the position of the picture placement int x = (Image.getwidth ()-Widthlogo)/2; int y = (image.getheight ()-Heightlogo)/2; 4, draw the picture graph.drawimage (logo, x, y, Widthlogo, Heightlogo, NULL); Graph.drawroundrect (x, Y, Widthlogo, Heightlogo, 10, 10); Graph.setstroke (New Basicstroke (Logoconfig.getborder ())); Graph.setcolor (Logoconfig.getbordercolor ()); Graph.drawrect (x, Y, Widthlogo, Heightlogo); Graph.dispose (); Imageio.write (image, "JPEG", New File ("c:/users/admin/desktop/code/newpic.jpg")); } catch (Exception e) {System.out.println (e); } }
Let's write a test class to test
@Testpublic void test() { QrCodeUtils.createQrCode(100, 100, "你好,世界"); QrCodeUtils.readQrCode("C:\\Users\\admin\\Desktop\\code\\4ad3a0a4-8d5c-4cd3-9ee5-5f680233a33f.png"); QrCodeUtils.createLogoQrCode(300, 300, "https://www.jianshu.com/u/f84a2d49420b"); QrCodeUtils.readQrCode("C:\\Users\\admin\\Desktop\\code\\newPic.jpg"); }
I'm not going to let you build a good QR code, you can try it yourself.
We add a tool function that reads the contents of the QR code
/** * Parse QR code * * @param codepath QR Code store full Path * */public static void Readqrcod E (String codepath) {try {multiformatreader formatreader = new Multiformatreader (); File QRCode = new file (Codepath); BufferedImage image = Imageio.read (QRCode); Binarybitmap Binarybitmap = new Binarybitmap (new Hybridbinarizer (new Bufferedimageluminancesource (image)); Set the parameters of the QR code HashMap hints = new HashMap (); Hints.put (Encodehinttype.character_set, "utf-8"); Result result = Formatreader.decode (Binarybitmap, hints); Print analytic results System.out.println (result.tostring ()); Print two-dimensional code format SYSTEM.OUT.PRINTLN (Result.getbarcodeformat ()); Two-dimensional code text content System.out.println (Result.gettext ()); } catch (Exception e) {System.out.println (e); } }
Note: QR code is a certain error correction ability, you can put the QR code p into the style you like
Java implements a QR code with logo