QR codes are increasingly used and can be seen in many places, such as train tickets and promotional products. The following describes how to use Java to generate and decode QR codes.
1. Open-Source Projects:
Zxing: An open-source Java class library is used to parse 1D/2D bar codes in multiple formats. The goal is to decode the 1D barcode of QR code, data matrix, and UPC. It provides clients on multiple platforms, including j2se, j2se, and Android. --- UsedDecoding qrcode
D-Project: Kazuhiko arase's personal project (who is not clear about it, Japan), provides a wide range of configuration parameters, which are very flexible --- usedGenerate QR code
2 ,:
Generate QR code
Decodes QR code
3. Use D-project to generate qrcdoe
1) Introduce com. d_project.qrcode.jar into the project
2) qrcodeaction code:
Public void generate (requestcontext RC) throws unsupportedencodingexception, ioexception, servletexception {// string data = RC. param ("data", "http://osctools.net/qr"); // output image type string output = RC. param ("output", "image/JPEG"); int type = RC. param ("type", 4); If (type <0 | 10 <type) {return;} int margin = RC. param ("margin", 10); If (margin <0 | 32 <margin) {return;} int cellsize = RC. param ("size", 4); If (cellsize <1 | 4 <cellsize) {return;} int errorcorrectlevel = 0; try {errorcorrectlevel = parseerrorcorrectlevel (RC, RC. param ("error", "H");} catch (exception e) {return;} COM. d_project.qrcode.qrcode qrcode = NULL; try {qrcode = getqrcode (data, type, errorcorrectlevel);} catch (exception e) {return;} If ("image/JPEG ". equals (output) {bufferedimage image = qrcode. createimage (cellsize, margin); RC. response (). setcontenttype ("image/JPEG"); outputstream out = new bufferedoutputstream (RC. response (). getoutputstream (); try {ImageIO. write (image, "Jpeg", out);} finally {out. close () ;}} else if ("image/PNG ". equals (output) {bufferedimage image = qrcode. createimage (cellsize, margin); RC. response (). setcontenttype ("image/PNG"); outputstream out = new bufferedoutputstream (RC. response (). getoutputstream (); try {ImageIO. write (image, "PNG", out);} finally {out. close () ;}} else if ("image/GIF ". equals (output) {gifimage image = creategifimage (qrcode, cellsize, margin); RC. response (). setcontenttype ("image/GIF"); outputstream out = new bufferedoutputstream (RC. response (). getoutputstream (); try {image. write (out);} finally {out. close () ;}} else {return ;}} Private Static int parseerrorcorrectlevel (requestcontext RC, string ECL) {If ("L ". equals (ECL) {return errorcorrectlevel. l;} else if ("Q ". equals (ECL) {return errorcorrectlevel. q;} else if ("M ". equals (ECL) {return errorcorrectlevel. m;} else if ("H ". equals (ECL) {return errorcorrectlevel. h;} else {Throw RC. error ("qr_error_correct_error") ;}} Private Static qrcode getqrcode (string text, int typenumber, int errorcorrectlevel) throws illegalargumentexception {If (typenumber = 0) {return qrcode. getminimumqrcode (text, errorcorrectlevel);} else {qrcode QR = new qrcode (); QR. settypenumber (typenumber); QR. seterrorcorrectlevel (errorcorrectlevel); QR. adddata (text); QR. make (); Return QR ;}} Private Static gifimage creategifimage (qrcode, int cellsize, int margin) throws ioexception {int imagesize = qrcode. getmodulecount () * cellsize + margin * 2; gifimage image = new gifimage (imagesize, imagesize); For (INT y = 0; y <imagesize; y ++) {for (INT x = 0; x <imagesize; X ++) {If (margin <= x & x <imagesize-margin & margin <= Y & Y <imagesize-margin) {int Col = (X-margin)/cellsize; int ROW = (Y-margin)/cellsize; If (qrcode. isdark (row, col) {image. setpixel (X, Y, 0);} else {image. setpixel (X, Y, 1) ;}} else {image. setpixel (X, Y, 1) ;}} return image ;}
3) Front-end page:
<SCRIPT type = "text/JavaScript" src = "/JS/jquery. form-2.82.js "> </SCRIPT> <SCRIPT type =" text/JavaScript "> $ (document ). ready (function () {$ ("# submit "). click (function () {var url = "/Action/qrcode/generate? "+ $ (" # Qrcode_form "). serialize (); $ (". qrcodediv IMG "). ATTR ("src", URL + "&" + new date (). gettime (); $ ("# gen_url "). ATTR ("href", URL) ;}; $ ("# zxing "). popover ({'title': 'bar code processing class library zxing', 'content': 'zxing is an open source Java class library used to parse 1D/2D code codes in multiple formats. The goal is to decode the 1D barcode of QR code, data matrix, and UPC. It provides clients on multiple platforms, including j2se, j2se, and Android. ', 'Placement': 'bottom '});}); </SCRIPT> <Div id = "maincontent" class = "wrapper"> <Div class = "toolname"> Generate a QR code (QR code) Online) -Use <a id = "zxing" href = "http://www.oschina.net/p/zxing"> zxing </a> and <a href = "http://www.d-project.com/"> D-project </a> <a data -Toggle = "Modal" href = "# advice" style = "float: right; text-Decoration: none; "> <SPAN class =" Badge badge-important "> <I class =" icon-envelope icon-white "> </I> feedback </span> </a> </Div> <Div class = "toolusing Clearfix"> <Div class = "toolstab Clearfix"> <ul class = "nav-Tabs"> <li class = "active"> <a href = "/QR"> QR code conversion </a> </LI> <li> <a href = "/QR? Type = 2 "> QR code decoding </a> </LI> </ul> <Div class =" clear "> </div> <Form ID =" qrcode_form "method =" Post "> <Div class =" leftbar "> <Div class =" title "> URL or other text: </div> <textarea class = "input-xlarge" name = "data" onfocus = "If (this. value = 'HTTP: // osctools.net/qr') {This. value = '';}; this. select (); "onblur =" (This. value = '')? This. value = 'HTTP: // osctools.net/qr':this.value; "> http://osctools.net/qr </textarea> </div> <Div class =" operatelr "> <Div class =" optdetail span1 "> <label> output format: </label> <select name = "output" class = "span1"> <option value = "image/GIF" selected> GIF </option> <option value = "image/ JPEG "> JPEG </option> <option value =" image/PNG "> PNG </option> </SELECT> <label> Error Correction level: </label> <select name = "error" class = "span1"> <OPT Ion value = "L" selected> L 7% </option> <option value = "M"> M 15% </option> <option value = "Q"> q 25% </ option> <option value = "H"> H 30% </option> </SELECT> <label> type: </label> <select name = "type" class = "span1"> <option value = "0"> automatic </option> <option value = "1"> 1 </option> <option value = "2"> 2 </option> <option value = "3"> 3 </option> <option value = "4"> 4 </ option> <option value = "5"> 5 </option> <option value = "6"> 6 </opti On> <option value = "7"> 7 </option> <option value = "8"> 8 </option> <option value = "9"> 9 </Option> <option value = "10"> 10 </option> </SELECT> <label> edge WHITE: </label> <select name = "margin" class = "span1"> <option value = "0"> 0 </option> <option value = "1"> 1 </option> <option value = "2"> 2 </option> <option value = "3"> 3 </option> <option value = "4"> 4 </ option> <option value = "5"> 5 </option> <option value = "6"> 6 </option> <Option Value = "7"> 7 </option> <option value = "8"> 8 </option> <option value = "9"> 9 </option> <option value = "10"> 10 </option> <option value = "11"> 11 </option> <option value = "12"> 12 </option> <option value = "13"> 13 </option> <option value = "14"> 14 </option> <option value = "15"> 15 </option> <option value =" 16 "> 16 </option> <option value =" 17 "> 17 </option> <option value =" 18 "> 18 </option> <option value =" 19 "> 19 </option> <option va Lue = "20"> 20 </option> <option value = "21"> 21 </option> <option value = "22"> 22 </option> <option value = "23"> 23 </option> <option value = "24"> 24 </option> <option value = "25"> 25 </option> <option value = "26"> 26 </option> <option value = "27"> 27 </option> <option value = "28"> 28 </option> <option value =" 29 "> 29 </option> <option value =" 30 "> 30 </option> <option value =" 31 "> 31 </option> <option value =" 32 "> 32 </option> </selec T> <label> original cell size: </label> <select name = "size" class = "span1"> <option value = "1"> 1 </option> <option value = "2"> 2 </option> <option value = "3"> 3 </option> <option value = "4" selected> 4 </option> </SELECT> <button class = "BTN BTN-small BTN-primary "id =" Submit "onclick =" Return false; "> Generate a QR code </button> </div> <Div class =" rightbar "> <Div class =" title "> QR code: </div> <Div class = "qrcodediv"> <Div class = "qrwrapper "> <A id =" gen_url "href ="/Action/qrcode/generate? Size = 4 "target =" _ blank "> </a> </div> </form> </div>
4. Use zxing to decode qrcode
1. Download zxing-2.0.zip
2) Introduce zxing-barcode_core.jar and zxing_barcode_j2se.jar to the Project
3) qrcodeaction code:
@ Postmethod @ jsonoutputenabledpublic void decode (requestcontext RC) throws ioexception {// URL with qrcode: String url = RC. param ("url", ""); // qrcdoe image file IMG = RC. file ("qrcode"); If (stringutils. isblank (URL) & IMG = NULL) {Throw RC. error ("qr_upload_or_url_null");} List <result> Results = new arraylist <result> (); config Config = new config (); inputs Inputs = new inputs (); config. sethints (buildhints (con Fig); If (stringutils. isnotblank (URL) {addargumenttoinputs (URL, config, inputs);} If (IMG! = NULL) {inputs. addinput (IMG. getCanonicalPath ();} while (true) {string input = inputs. getnextinput (); If (input = NULL) {break;} file inputfile = new file (input); If (inputfile. exists () {try {result = decode (inputfile. touri (), config, RC); results. add (result);} catch (ioexception e) {}} else {try {result = decode (New uri (input), config, RC); results. add (result);} catch (exception e) {}} RC. Print (New gson (). tojson (results);} private result decode (URI Uri, config, requestcontext RC) throws ioexception {Map <decodehinttype,?> Hints = config. gethints (); bufferedimage image; try {image = ImageIO. read (URI. tourl ();} catch (illegalargumentexception IAE) {Throw RC. error ("qr_resource_not_found");} If (image = NULL) {Throw RC. error ("reported");} Try {luminancesource source = new bufferedimageluminancesource (image); binarybitmap bitmap = new binarybitmap (New hybridbinarizer (source); Result result = new multiformatre Ader (). decode (bitmap, hints); return result;} catch (notfoundexception NFE) {Throw RC. error ("qr_no_barcode_found") ;}} Private Static Map <decodehinttype,?> Buildhints (config) {Map <decodehinttype, Object> hints = new enummap <decodehinttype, Object> (decodehinttype. class); collection <barcodeformat> vector = new arraylist <barcodeformat> (8); vector. add (barcodeformat. upc_a); vector. add (barcodeformat. upc_e); vector. add (barcodeformat. ean_13); vector. add (barcodeformat. ean_8); vector. add (barcodeformat. rss_14); vector. add (barcodeformat. rss_expanded); If (! Config. isproductsonly () {vector. add (barcodeformat. code_39); vector. add (barcodeformat. code_93); vector. add (barcodeformat. code_128); vector. add (barcodeformat. ITF); vector. add (barcodeformat. qr_code); vector. add (barcodeformat. data_matrix); vector. add (barcodeformat. aztec); vector. add (barcodeformat. pdf_417); vector. add (barcodeformat. codabar); vector. add (barcodeformat. maxicode);} hints. put (decodehinttype. possible_formats, vector); If (config. istryharder () {hints. put (decodehinttype. try_harder, Boolean. true);} If (config. ispurebarcode () {hints. put (decodehinttype. pure_barcode, Boolean. true);} return hints;} Private Static void addargumenttoinputs (string argument, config, inputs Inputs) throws ioexception {file inputfile = new file (argument); If (inputfile. exists () {inputs. addinput (inputfile. getCanonicalPath ();} else {inputs. addinput (argument );}}
4) Front-end page:
<SCRIPT type = "text/JavaScript" src = "/JS/jquery. form-2.82.js "> </SCRIPT> <SCRIPT type =" text/JavaScript "> $ (document ). ready (function () {$ ("# qrcode_form "). ajaxform ({success: function (JSON) {If (JSON = NULL) return; JSON = eval ("(" + JSON + ")"); If (JSON. MSG) {alert (JSON. MSG); return;} If (JSON [0]) $ ("# result "). val (JSON [0]. text); else $ ("# result "). val ("decoding failed") ;}}; $ ("# zxing "). popover ({'title': 'bar code processing class library zxing', 'conte NT ': 'zxing is an open-source Java class library used to parse 1D/2D code codes in multiple formats. The goal is to decode the 1D barcode of QR code, data matrix, and UPC. It provides clients on multiple platforms, including j2se, j2se, and Android. ', 'Placement': 'bottom '});}); </SCRIPT> <Div id = "maincontent" class = "wrapper"> <Div class = "toolname"> Generate a QR code (QR code) Online) -Use <a id = "zxing" href = "http://www.oschina.net/p/zxing"> zxing </a> and <a href = "http://www.d-project.com/"> D-project </a> <a data -Toggle = "Modal" href = "# advice" style = "float: right; text-Decoration: none; "> <SPAN class =" Badge badge-important "> <I class =" icon-envelope icon-white "> </I> feedback </span> </a> </Div> <Div class = "toolusing Clearfix"> <Div class = "toolstab Clearfix"> <ul class = "nav-Tabs"> <li> <a href =" /QR "> convert QR code </a> </LI> <li class =" active "> <a href ="/QR? Type = 2 "> QR code decoding </a> </LI> </ul> <Div class =" clear "> </div> <Form ID =" qrcode_form "method =" Post "Action ="/Action/qrcode/decode "> <Div class =" topbar "> <Div class =" title "> <label class =" radio "For =" upload_url "> image URL: <input checked = "checked" name = "upload_ctn" id = "upload_url" style = "margin-Right: 5px;" type = "radio" onchange = "If (this. checked) {$ ('input [name = \ 'url \ ']'). removeattr ('Disabled '); $ ('input [name = \ 'Qrcode \ ']'). ATTR ('Disabled ', 'Disabled')} "/> </label> </div> <input name =" url "id =" url "style =" width: 100%; Height: 40px; margin: 0 0 10px 0; "onfocus =" If (this. value = 'HTTP: // www.osctools.net/img/qr.gif') {This. value = '';}; this. select (); "onblur =" (This. value = '')? This. value = 'HTTP: // www.osctools.net/img/qr.gif':this.value; "value =" http://www.osctools.net/img/qr.gif "/> <Div class =" title "> <label class =" radio "for =" upload_img "> upload image: <input style = "margin-Right: 5px;" name = "upload_ctn" id = "upload_img" type = "radio" onchange = "If (this. checked) {$ ('input [name = \ 'qrcode \ ']'). removeattr ('Disabled '); $ ('input [name = \ 'url \'] '). ATTR ('Disabled ', 'Disabled ')} "/> </label> </div> <input Disabled =" disabled "name =" qrcode "type =" file "class =" input-file "/> <input class = "BTN-primary" value = "decoding" type = "Submit"/> </div> <Div class = "bottombar"> <Div class = "title"> Decoding result: </div> <textarea id = "result"> </textarea> </div> </form> </div>
Note: The requestcontext class involved is shown here: http://www.oschina.net/code/snippet_12_2