java生成自定義標誌、大小的二維碼

前段時間沒事忽然看到有些宣傳海報上面打印了帶log的二維碼,因而在網上查找了生成二維碼的方法,本身進行了寫修改,下面直接貼出代碼供參考:java

注:要引入QRCode.jar包數組

一、這是生成二維碼的處理類:QRCodeEncoderHandler測試

package com.czp.commonutil;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.czp.QRCode.pro.TwoDimensionCodeImage;
import com.czp.logQRcode.LogoConfig;
import com.czp.logQRcode.MatrixToImageWriter;
import com.czp.util.CommonUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.swetake.util.Qrcode;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
public class QRCodeEncoderHandler {
    /**  
     * 生成二維碼(QRCode)圖片的公共方法  
     * @param content 存儲內容  
     * @param imgType 圖片類型  
     * @param size 二維碼尺寸  
     * @param addLog 是否添加log
     * @param addText 添加的文字
     * @return  
     */ 
     @SuppressWarnings("unchecked")
    public synchronized static String qRCodeCommon(String content, String imgType, int size,Boolean addLog,String addText) {
            final  String uploadRootDir="D:/temp/";//臨時文件夾
            final  String uploadPathImg="D:/imgfile";//存儲文件夾
            final  String path = "E:/QRCodeImage";//存放logo的文件夾
            String fileDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String name=CommonUtil.getSysFormatTime("yyyyMMddHHmmssSSS").toString();//圖片名稱
            final String  uploadPath =uploadPathImg+ "/"+fileDate+"/";//+priBankCode+"/"

            BufferedImage bufImg = null;  
            String fileNamePath=uploadPath+"";//返回生成二維碼路徑、名稱
            int imgSize=1;
            //size = 2;  
            try {  
                Qrcode qrcodeHandler = new Qrcode();  
                // 設置二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小  
                qrcodeHandler.setQrcodeErrorCorrect('M');  
                qrcodeHandler.setQrcodeEncodeMode('B');  
                // 設置設置二維碼尺寸,取值範圍1-40,值越大尺寸越大,可存儲的信息越大  
                qrcodeHandler.setQrcodeVersion(size);  
                // 得到內容的字節數組,設置編碼格式  
                byte[] contentBytes = content.getBytes("utf-8");  
                // 圖片尺寸  
                imgSize = 67 + 12 * size;  
                System.out.println("imgSize:"+imgSize);
                bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);  
                Graphics2D gs = bufImg.createGraphics();  
                // 設置背景顏色  
                gs.setBackground(Color.WHITE);  
                gs.clearRect(0, 0, imgSize, imgSize);  

                // 設定圖像顏色> BLACK  
                gs.setColor(Color.BLACK);  
                // 設置偏移量,不設置可能致使解析出錯  
                int pixoff = 2;  
                // 輸出內容> 二維碼  
                if (contentBytes.length > 0 && contentBytes.length < 200) {  

                    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 {  
                    System.out.println("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");  
                    throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");  
                }  
                gs.dispose();  
                bufImg.flush();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            File uploadDir = new File(uploadPath);
            if(!uploadDir.exists()){
                uploadDir.mkdirs();
            }
            if(addLog && ""!=addText ) {//當要同時寫入log和文字
                //storageQRCodeIMG(bufImg,uploadRootDir,name+"_Temp.PNG");//將生成二維碼圖片存入臨時文件夾
                MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                @SuppressWarnings("rawtypes")
                Map hints = new HashMap();
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //設置UTF-8, 防止中文亂碼
                hints.put(EncodeHintType.MARGIN,1); //設置二維碼四周白色區域的大小
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);   //設置二維碼的容錯性
                //width:圖片完整的寬;height:圖片完整的高
                //由於要在二維碼下方附上文字,因此把圖片設置爲長方形(高大於寬)
               // int width = 400;
               // int height = 450;
                //畫二維碼,記得調用multiFormatWriter.encode()時最後要帶上hints參數,否則上面設置無效
                BitMatrix bitMatrix=null;
                try {
                    bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
                } catch (WriterException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
              //qrcFile用來存放生成的二維碼圖片(無logo,無文字)
                File qrcFile = new File(uploadRootDir,name+"_Temp.PNG");
                //logoFile用來存放帶有logo的圖片
                File logoFile = new File(path,"QQ.PNG");//log圖片

                //開始畫二維碼
                try {
                    MatrixToImageWriter.writeToFile(bitMatrix, "PNG", qrcFile);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //在二維碼中加入圖片
                LogoConfig logoConfig = new LogoConfig(); //LogoConfig中設置Logo的屬性
                addLogo_QRCode(qrcFile, logoFile, logoConfig,uploadRootDir,name+"_imageWithLogTemp.PNG");//向生成的二維碼圖片加入log,並寫入臨時文件夾

                //用來存放帶有logo+文字的二維碼圖片的路徑
                String withLogAndTextName =name+ "_imageWithText.PNG"; 
                //帶有logo的二維碼圖片
                String targetImage = uploadRootDir+name+"_imageWithLogTemp.PNG";
                pressText(addText,targetImage, 1,Color.BLUE, 10, imgSize, imgSize, uploadPath,withLogAndTextName);
                fileNamePath+=withLogAndTextName;
            //  new File(uploadRootDir+name).delete();//刪除原先的圖片     
            }else if(!addLog && ""!=addText) {//只添加文字時
                //storageQRCodeIMG(bufImg,uploadRootDir,name+"_Temp.PNG");//將生成二維碼圖片存入臨時文件夾
                 MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                    @SuppressWarnings("rawtypes")
                    Map hints = new HashMap();
                    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //設置UTF-8, 防止中文亂碼
                    hints.put(EncodeHintType.MARGIN,1); //設置二維碼四周白色區域的大小
                    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);   //設置二維碼的容錯性
                    //width:圖片完整的寬;height:圖片完整的高
                    //由於要在二維碼下方附上文字,因此把圖片設置爲長方形(高大於寬)
                    //int width = 400;
                   // int height = 450;
                    //畫二維碼,記得調用multiFormatWriter.encode()時最後要帶上hints參數,否則上面設置無效
                    BitMatrix bitMatrix=null;
                    try {
                        bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
                    } catch (WriterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                  //qrcFile用來存放生成的二維碼圖片(無logo,無文字)
                    File qrcFile = new File(uploadRootDir,name+"_Temp.PNG");
                    //開始畫二維碼
                    try {
                        MatrixToImageWriter.writeToFile(bitMatrix, "PNG", qrcFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                 //用來存放帶有logo+文字的二維碼圖片的路徑
                String withTextName =name+ "_withText.PNG"; 
                //生成的二維碼圖片
                String targetImage = uploadRootDir+name+"_Temp.PNG";
                pressText(addText,targetImage, 1,Color.BLUE, 18, imgSize, imgSize, uploadPath,withTextName);
                fileNamePath+=withTextName;
            }else if(addLog && ""==addText){//只添加log圖片
                //storageQRCodeIMG(bufImg,uploadRootDir,name+"_Temp.PNG");//將生成二維碼圖片存入臨時文件夾
                 MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                    @SuppressWarnings("rawtypes")
                    Map hints = new HashMap();
                    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //設置UTF-8, 防止中文亂碼
                    hints.put(EncodeHintType.MARGIN,1); //設置二維碼四周白色區域的大小
                    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);   //設置二維碼的容錯性
                    //width:圖片完整的寬;height:圖片完整的高
                    //由於要在二維碼下方附上文字,因此把圖片設置爲長方形(高大於寬)
                    //int width = 400;
                   // int height = 450;
                    //畫二維碼,記得調用multiFormatWriter.encode()時最後要帶上hints參數,否則上面設置無效
                    BitMatrix bitMatrix=null;
                    try {
                        bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
                    } catch (WriterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                  //qrcFile用來存放生成的二維碼圖片(無logo,無文字)
                    File qrcFile = new File(uploadRootDir,name+"_Temp.PNG");
                    //logoFile用來存放帶有logo的圖片
                    File logoFile = new File(path,"QQ.PNG");//log圖片

                    //開始畫二維碼
                    try {
                        MatrixToImageWriter.writeToFile(bitMatrix, "PNG", qrcFile);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //用來存放生成二維碼的路徑
                    String WithLogName =name+"_imageWithLog.PNG";
                    //在二維碼中加入圖片
                    LogoConfig logoConfig = new LogoConfig(); //LogoConfig中設置Logo的屬性
                    addLogo_QRCode(qrcFile, logoFile, logoConfig,uploadPath,WithLogName);//向生成的二維碼圖片加入log
                    fileNamePath+=WithLogName;
            }else if(!addLog && ""==addText) {//只生成二維碼
                storageQRCodeIMG(bufImg,uploadPath,name+".PNG");//將生成二維碼圖片存入文件夾
                 fileNamePath+=name+".PNG";
            }
            return fileNamePath;  
        }  

     /** 
         * 存儲二維碼至指定路徑(storageQRCodeIMG) 
         * @param bufImg 圖片
         * @param path 圖片路徑 
         * @param name 圖片名稱
         */  
     public static void storageQRCodeIMG(BufferedImage bufImg,String path,String name) {
         if(".PNG".lastIndexOf(name)!=-1 || ".png".lastIndexOf(name)!=-1) {
             name=name+".PNG";
         }
         File imgFile = new File(path+name);
         // 生成二維碼QRCode圖片 
         try {
            ImageIO.write(bufImg, "PNG", imgFile);
        } catch (IOException e) {
            e.printStackTrace();
        } 
     }
     /** 
         * 解析二維碼(QRCode) 
         * @param imgPath 圖片路徑 
         * @return 
         */  
      public String decoderQRCode(String imgPath) {  
            // QRCode 二維碼圖片的文件  
            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());  
                dfe.printStackTrace();  
            }  
            return content;  
        }  

      /**
         * 給二維碼圖片添加Logo
         * 
         * @param qrPic 要添加log的二維碼
         * @param logoPic log圖片
         *@param logoConfig log參數
         *@param  newImgPath 新生成圖片存儲路徑
         *@param  newImgName 新生成圖片名稱
         */
        public static void addLogo_QRCode(File qrPic, File logoPic, LogoConfig logoConfig,String newImgPath,String newImgName)
        {
            try
            {
                if (!qrPic.isFile() || !logoPic.isFile())
                {
                    System.out.print("file not find !");
                    System.exit(0);
                }

                /**
                 * 讀取二維碼圖片,並構建繪圖對象
                 */
                BufferedImage image = ImageIO.read(qrPic);
                Graphics2D g = image.createGraphics();

                /**
                 * 讀取Logo圖片
                 */
                BufferedImage logo = ImageIO.read(logoPic);

                int widthLogo = image.getWidth()/logoConfig.getLogoPart(); 
            //    int    heightLogo = image.getHeight()/logoConfig.getLogoPart();
                int    heightLogo = image.getWidth()/logoConfig.getLogoPart(); //保持二維碼是正方形的

                // 計算圖片放置位置
                int x = (image.getWidth() - widthLogo) / 2;
                int y = (image.getHeight() - heightLogo) / 2 ;        


                //開始繪製圖片
                g.drawImage(logo, x, y, widthLogo, heightLogo, null);
                g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
                g.setStroke(new BasicStroke(logoConfig.getBorder()));
                g.setColor(logoConfig.getBorderColor());
                g.drawRect(x, y, widthLogo, heightLogo);

                g.dispose();
                image.flush();  
                //將加入log的圖片寫入指定路徑
                storageQRCodeIMG(image,newImgPath,newImgName);
              //  ImageIO.write(image, "PNG", new File("D:/newPic.PNG"));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        /**
         * @爲圖片添加文字
         * @param pressText 文字
         * @param targetImg 須要添加文字的圖片
         * @param fontStyle 須要添加文字的字體風格
         * @param color     字體顏色
         * @param fontSize  字體大小
         * @param width     生成圖片寬度
         * @param heigh     生成圖片高度
         * @param newImgPath    新生成的圖片存儲路徑
         * @param newImgName    新生成的圖片名稱
         */
        public static void pressText(String pressText,String targetImg, int fontStyle, Color color, int fontSize, int width, int height,String newImgPath ,String newImgName) {
             //設置一個默認長度和寬度
            // width = 400;
           //  height = 450;


            //計算文字開始的位置
            //x開始的位置:(圖片寬度-字體大小*字的個數)/2
            int startX = (width-(fontSize*pressText.length()))/2;
            //y開始的位置:圖片高度-(圖片高度-圖片寬度)/2
            int startY = height-(height-width)/2-5;        

            try {
                File file = new File(targetImg);
                Image src = ImageIO.read(file);
                int imageW = src.getWidth(null);
                int imageH = src.getHeight(null);
                BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
                Graphics g = image.createGraphics();
                g.drawImage(src, 0, 0, imageW, imageH, null);
                g.setColor(color);
                g.setFont(new Font(null, fontStyle, fontSize));
                g.drawString(pressText, startX, startY);
                g.dispose();
                image.flush();

              //將加入文字的圖片寫入指定路徑
                storageQRCodeIMG(image,newImgPath,newImgName);

                /*FileOutputStream out = new FileOutputStream(newImg);
                ImageIO.write(image, "PNG", out);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.close();*/
                System.out.println("image press success");
            } catch (Exception e) {
                System.out.println(e);
            }
        }
}

二、下面是測試類:字體

package com.czp.QRCodeTest;

import com.czp.commonutil.QRCodeEncoderHandler;

public class testQRCode {
    public static void main(String[] args) {
        /*File fileDir = new File("D:/imgfile/"); 
        fileDir.mkdirs(); */
        QRCodeEncoderHandler qr=new QRCodeEncoderHandler();

        //BufferedImage BIM=qr.qRCodeCommon("xx很帥!哈哈。。。","PNG",5,true,"");
        //TwoDimensionCode TDC=new TwoDimensionCode();

        //String pathName1=qr.qRCodeCommon("xx很帥!哈哈。。。","PNG",5,false,"");//只生成帶二維碼
        //String pathName2=qr.qRCodeCommon("xx很帥!哈哈。。。","PNG",5,true,"");//只生成帶log的
        String pathName3=qr.qRCodeCommon("408120","PNG",18,true,"仙女專用");//只生成帶log和文字的
        //String pathName4=qr.qRCodeCommon("xx很帥!哈哈。。。","PNG",5,false,"123測試");//只生成帶文字的

        //System.out.println("pathName1:"+pathName1);
        //System.out.println("pathName2:"+pathName2);
        System.out.println("pathName3:"+pathName3);
        //System.out.println("pathName4:"+pathName4);

        //System.out.println("二維碼信息:"+TDC.decoderQRCode("D:/imgfile/20171110172958.png"));//進行二維碼信息的解析
        //System.out.println(BIM.toString());



    }

}

三、下面是生成的二維碼示例:google

相關文章
相關標籤/搜索