Java QR code generation and decoding based on Google zxing
One, add maven dependency (decoding need to upload two-dimensional code image, so you need to rely on File upload package)
<!--google QR code tool -<Dependency> <groupId>Com.google.zxing</groupId> <Artifactid>Javase</Artifactid> <version>3.1.0</version></Dependency><!--File Upload -<Dependency> <groupId>Commons-fileupload</groupId> <Artifactid>Commons-fileupload</Artifactid> <version>1.3.1</version></Dependency><Dependency> <groupId>Commons-io</groupId> <Artifactid>Commons-io</Artifactid> <version>2.4</version></Dependency>
Second, create the generation of two-dimensional Code interface (interface parameters for the two-dimensional code content, usually URL)
/*** Generate QR Code * Google zxing Implementation *@paramtext *@return */@RequestMapping (Value= "/qrcode/encode", method =requestmethod.post) Public voidEncodeqrcode (String text, httpservletresponse response) {Try { //set the QR code parameterMap<encodehinttype, object> hints =NewHashmap<encodehinttype, object>(); Hints.put (Encodehinttype.character_set,"UTF-8"); Bitmatrix Bitmatrix=NewMultiformatwriter (). Encode (text, Barcodeformat.qr_code, 150, 150, hints); //back to QR codeMatrixtoimagewriter.writetostream (Bitmatrix, "JPG", Response.getoutputstream ()); } Catch(Exception e) {e.printstacktrace (); }}
Third, create two-dimensional code decoding interface (directly return the decoded QR code content)
/*** QR code image decoding * Google zxing implementation *@paramqrimg *@return */@RequestMapping (Value= "/qrcode/decode", method =requestmethod.post) PublicString Decodeqrcode (multipartfile qrimg) {if(!Qrimg.isempty ()) { Try{bufferedimage image=Imageio.read (Qrimg.getinputstream ()); Binarybitmap Binarybitmap=NewBinarybitmap (NewHybridbinarizer (NewBufferedimageluminancesource (image)); //define the parameters of the QR code:Hashmap<decodehinttype, object> hints =NewHashmap<>(); //Defining character SetsHints.put (Decodehinttype.character_set, "Utf-8"); Result result=NewMultiformatreader (). Decode (Binarybitmap, hints); returnResult.gettext (); } Catch(Exception e) {e.printstacktrace (); } } return NULL;}
Java Two-dimensional code generation and decoding