Java generates two-dimensional code to achieve scan count and forward to an address

Source: Internet
Author: User
Tags getmessage set background

Requirements: In recent days a project requires users to enter their own web site, and then the system needs to generate two-dimensional code according to the user's URL, then the user can take it to others to scan, access to his input URL, in the process. I need to know the number of times the user's QR code was scanned , That is, you can do some sort of scan ranking in the back.

Ideas:

    1. Mister into two-dimensional code, CSDN already have predecessors wrote, then I directly take over to use.
    2. The user's ID, and the user input URL is processed as an HTTP GET parameter in the QR code, then the user scan will automatically jump to one of our system interface
    3. In the interface according to the user ID of the user query out, the number of scans plus 1 redirect to the user input page

Code implementation:1. The generation of two-dimensional code part, citing the achievements of the predecessors, point to praise, with a good feeling!
Package Javacommon.qrcode;import Java.awt.color;import Java.awt.graphics2d;import java.awt.image.BufferedImage; Import Java.io.file;import java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.io.unsupportedencodingexception;import Javax.imageio.imageio;import Org.junit.test;import Jp.sourceforge.qrcode.qrcodedecoder;import Jp.sourceforge.qrcode.exception.decodingfailedexception;import com.swetake.util.qrcode;/** * Create a QR Code tool class and change the class to a static tool class * @author Bill * @see source from: http://blog.csdn.net/wangpeng047/article/ details/7181217 * @since V1.0 2014/01/07 */public class Twodimensioncode {/*private Twodimensioncode () {}*//** * Generate two-dimensional code (QRC ODE) Pictures * @param content Store Contents * @param imgpath picture path */public static void Encoderqrcode (string content, String imgpath) {ENC Oderqrcode (content, Imgpath, "PNG", 7);} /** * Generate QR Code (qrcode) picture * @param Content Store contents * @param output stream */public static void Encoderqrcode (String content, OutputS Tream output) {encoderqrcode (content, Output, "PNG", 7);} /** * Generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture path * @param imgtype picture type */public static void Encoderqrcode (string content, String Imgpath, String imgtype) {Encoderqrcode (content, Imgpath, Imgtype, 7);} /** * Generate QR Code (qrcode) picture * @param content storage * @param output stream * @param imgtype picture type */public static void Encoderqrcode (S Tring content, OutputStream output, String imgtype) {encoderqrcode (content, output, imgtype, 7);} /** * Generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture path * @param imgtype Picture type * @param size QR code dimensions */public Stati c void Encoderqrcode (string content, String Imgpath, string imgtype, int size) {try {bufferedimage bufimg = Qrcodecommon (c Ontent, imgtype, size); File Imgfile = new file (imgpath);//generate QR code qrcode picture Imageio.write (bufimg, Imgtype, imgfile);} catch (Exception e) {e.printstacktrace ();}} /** * Generate QR Code (qrcode) picture * @param content storage * @param output stream * @param imgtype Picture type * @param size QR code size */public static void Encoderqrcode (String content, OUTPUtstream output, String imgtype, int size) {try {bufferedimage bufimg = Qrcodecommon (content, imgtype, size)//generate QR code qrcod E picture Imageio.write (bufimg, imgtype, Output);} catch (Exception e) {e.printstacktrace ();}} /** * Common methods for generating QR code (qrcode) images * @param content Store Contents * @param imgtype Picture type * @param size size 1-40, the larger the value, the greater the information that can be stored * @r Eturn */private static BufferedImage Qrcodecommon (string content, string imgtype, int size) {BufferedImage bufimg = null;t ry {QRCode Qrcodehandler = new QRCode ();//Set the two-dimensional code error rate, optional L (7%), M (15%), Q (25%), H (30%), the higher the error rate, the less information can be stored, However, the requirements for the definition of two-dimensional code are smaller qrcodehandler.setqrcodeerrorcorrect (' M '); Qrcodehandler.setqrcodeencodemode (' B ');//Set the size of the QR code, Value range 1-40, the larger the value size, the larger the information can be stored qrcodehandler.setqrcodeversion (size);//Get the content of the byte array, set the encoding format byte[] Contentbytes = Content.getbytes ("Utf-8");//Picture size int imgsize = + * (size-1); bufimg = new BufferedImage (imgsize, Imgsize, Bufferedi Mage. TYPE_INT_RGB); graphics2d GS = Bufimg.creategraphics ();//Set Background color gs.setbackground (color.white); gs.clearrect (0, 0, IMGsIze, imgsize);//Set Image Color > Blackgs.setcolor (color.black);//Set offset, not set may cause parsing error int pixoff = 2;//output content > QR code if ( Contentbytes.length > 0 && contentbytes.length < +) {boolean[][] codeout = Qrcodehandler.calqrcode (  Contentbytes); for (int i = 0, i < codeout.length; i++) {for (int j = 0; J < Codeout.length; J + +) {if (Codeout[j][i]) {Gs.fillrect (J * 3 + Pixoff, I * 3 + Pixoff, 3, 3);}}} else {throw new Exception ("qrcode content bytes Length =" + Contentbytes.length + "not in [0, 800].");} Gs.dispose (); Bufimg.flush ();} catch (Exception e) {e.printstacktrace ();} return bufimg;} /** * Parse QR code (qrcode) * @param imgpath picture path * @return */public static string Decoderqrcode (String imgpath) {//qrcode QR code picture Document file ImageFile = new file (Imgpath); BufferedImage bufimg = null; String content = null;try {bufimg = Imageio.read (ImageFile); Qrcodedecoder decoder = new Qrcodedecoder (), content = new String (Decoder.decode (New Twodimensioncodeimage (bufimg)), " Utf-8 "); } catch (IOException e) {SystEm.out.println ("Error:" + e.getmessage ()); E.printstacktrace ();} catch (Decodingfailedexception DfE) {System.out.println ("Error:" + dfe.getmessage ());d fe.printstacktrace ();} return content;} /** * Parse QR code (QRCODE) * @param input stream * @return */public static String decoderqrcode (InputStream input) {BufferedImage bu Fimg = null; String content = null;try {bufimg = Imageio.read (input); Qrcodedecoder decoder = new Qrcodedecoder (), content = new String (Decoder.decode (New Twodimensioncodeimage (bufimg)), " Utf-8 "); } catch (IOException e) {System.out.println ("Error:" + e.getmessage ()); E.printstacktrace ();} catch (Decodingfailedexception DfE) {System.out.println ("Error:" + dfe.getmessage ());d fe.printstacktrace ();} return content;} public static void Main (string[] args) {String Imgpath = "E:/01.png";//string encodercontent = "Hello big, small, welcome to QRC ode! "+" \nmyblog [http://sjsky.iteye.com] "+" \nemail [[email protected]] "; Twodimensioncode handler = new Twodimensioncode ();//handler.encoderqRCode (Encodercontent, Imgpath, "PNG"),//try {//outputstream output = new FileOutputStream (imgpath);// Handler.encoderqrcode (content, Output),//} catch (Exception e) {//e.printstacktrace ();//}//System.out.println ("= = ====encoder success "); String decodercontent = Handler.decoderqrcode (Imgpath); System.out.println ("Parse the result as follows:"); System.out.println (decodercontent); System.out.println ("========decoder success!!!");} @Testpublic void test01 () throws unsupportedencodingexception{string msg = "Http://baike.baidu.com/link?" yvwkhk4xqvwk444yx444yxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z 5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z 5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n 4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n 4aZGwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvw Khk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvw Khk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35sy xzxqmyvwkhk4n4azgwu6z5zxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n 4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgw u6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhk4n4azgwu6z5smy35syxzxqmyvwkhkikmbrht9-s2w Baebs haha where Lhasa's "; System.out.println ("Normal:" +msg.length ()); System.out.println ("bytes:" +msg.getbytes ("UTF-8"). length); Encoderqrcode (Msg.tostring (), "E:/2/t7.png", "PNG", 40) ; System.out.println ("OK");}}

Package Javacommon.qrcode;import Java.awt.image.bufferedimage;import Jp.sourceforge.qrcode.data.QRCodeImage; public class Twodimensioncodeimage implements Qrcodeimage {bufferedimage bufimg;public twodimensioncodeimage ( BufferedImage bufimg) {this.bufimg = bufimg;} @Overridepublic int getheight () {return bufimg.getheight ();} @Overridepublic int GetPixel (int x, int y) {return Bufimg.getrgb (x, y);} @Overridepublic int getwidth () {return bufimg.getwidth ();}}


There is also a jar package, attached: Http://pan.baidu.com/s/1jGmoshK

2. Generate QR code and provide an extranet access address method
<span style= "White-space:pre" ></span>/** * generates a QR code based on the address given by the user and stores it locally. Return to the outbound access address * @param Qrcodetargeturl user's incoming address * @param campaign Activity number * @return * @throws unsupportedencodingexception */priva Te string Generator2code (String Qrcodetargeturl,campaign Campaign) throws Unsupportedencodingexception {//TODO Implement QR code to create if (! Stringutils.isempty (Qrcodetargeturl)) {String Httpurl = Appconfig.getproperty ("Filevisiturl"); String Localurl = Appconfig.getproperty ("Uploadfilebasepath");//file name StringBuilder Userofurl = new StringBuilder (" qrcode/"), Userofurl.append (Campaign.getuser (). Getemail () +"/"); Userofurl.append (campaign.get_id () +"/"); New File ( Localurl + userofurl). Mkdirs ();//Create Folder Userofurl.append ("Qrcode.png");//Generate scan address StringBuilder qrcodescannerurl = new StringBuilder (); {Qrcodescannerurl.append (Appconfig.getproperty ("Qrcodescannerurl")); Qrcodescannerurl.append ("t=" + Urlencoder.encode (Qrcodetargeturl, "UTF-8")); Qrcodescannerurl.append ("&i=" +campaign.get_id ());} Long targeturllength = QRCOdescannerurl.tostring (). GetBytes ("UTF-8"). Length;int qrcodesize = 0;//control generated QR code size if (targeturllength <= 120) {// 7qrcodeSize = 7;} else if (targeturllength <= 410) {//15qrcodeSize = 15;} Else{qrcodesize = 20;//Here The maximum 20 is already able to meet the needs, the maximum can be set to 40}twodimensioncode.encoderqrcode (Qrcodescannerurl.tostring (), Localurl + userofurl, "png", qrcodesize); return httpurl + Userofurl; }return Stringutils.empty;}

3. All QR codes generated by the scan will be accessed by the interface, where scan statistics are performed.
/*** file name: qrcodecontroller.java* copyrights: Copyright 2014-2015 buyantech.all Rights reserved.* Description: Number of scans responsible for cumulative ads * Modified by: bill* Modified: 2014/01/07* Content modified: no */package com.buyantech.campaign.controller;import Java.io.ioexception;import Javacommon.base.basespringcontroller;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.lang.stringutils;import Org.apache.log4j.Logger ; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.Controller; Import Com.buyantech.campaign.model.campaign;import Com.buyantech.campaign.service.campaignmanager;import  com.buyantech.campaign.util.appconfig;/** * @author Bill * @since V1.0 2014/01/07 */@Controllerpublic class for cumulative ad Qrcodecontroller extends Basespringcontroller {@Autowiredprivate Campaignmanager campaignmanager; Logger Logger = Logger.getlogger (qrcodecontroller.class);/** * Used to increase the number of AD QR code scans, and forwarding * @param request * @param response * @thr OWS IOException */public void Q (HttpServletRequest request,httpservletresponse response) throws ioexception{string TargetUrl = Request.getparameter ("T");//Targerurl: Destination address string camId = Request.getparameter ("i");//CamId: Ad Number Boolean isaddsuccess = False;int scannersize = -1;if (! Stringutils.isempty (camId)) {Campaign Campaign = Campaignmanager.findbyid (camId); if (Campaign! = null) {scannersize = Campaign.getqrcodescancount () + 1;campaign.setqrcodescancount (scannersize); isaddsuccess = true; Campaignmanager.save (campaign);}} Determine if the cumulative success if (!isaddsuccess) {logger.error ("User scan destination QR code address is:" +targeturl+ ", scan cumulative record failed!");} Else{logger.info ("Ad ID:" +camid+ "is scanned, the current cumulative number is:" +scannersize);} To determine whether to carry an address, theoretically there is no empty address. May be hacker malicious modification, friendly hint!if (! Stringutils.isempty (TargetUrl)) {response.sendredirect (targeturl);} Else{response.getwriter (). Print ("
Well, it's almost there.

Java generates two-dimensional code to achieve scan count and forward to an address

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.