1. 程式人生 > >Java生成讀取條形碼和二維碼圖片(未測試)

Java生成讀取條形碼和二維碼圖片(未測試)

生成條形碼,二維碼圖片,解析條形碼,二維碼圖片的工具類,需要用到的jar包:core.jar,zxing-javase.jar

ZxingTool.java        

package zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author wiki
 */
public class ZxingTool {
    
    private static final int IMAGE_WIDTH = 80;  
    private static final int IMAGE_HEIGHT = 80;  
    private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
    private static final int FRAME_WIDTH = 2;  
    /**
     * 生成條形碼
     * @param contents 條形碼內容
     * @param width 條形碼寬度
     * @param height 條形碼高度
     * @return 
     */
    public static BufferedImage encodeBarcode(String contents, int width, int height){
        int codeWidth = 3 + // start guard
                (7 * 6) + // left bars
                5 + // middle guard
                (7 * 6) + // right bars
                3; // end guard
        codeWidth = Math.max(codeWidth, width);
        BufferedImage barcode = null;
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,BarcodeFormat.EAN_13, codeWidth, height, null);            
           barcode= MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return barcode;
    }
    
    /**
     * 解析讀取條形碼
     * @param barcodePath 條形碼檔案路徑
     * @return 
     */
    public static String decodeBarcode(String barcodePath){
        BufferedImage image;
        Result result = null;
        try {
            image = ImageIO.read(new File(barcodePath));
            if (image != null) {
                 LuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                result = new MultiFormatReader().decode(bitmap, null);
            }
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 生成二維碼
     * @param context 二維碼內容
     * @param width 二維碼圖片寬度
     * @param height 二維碼圖片高度
     * @return 
     */
    public static BufferedImage encodeQRcode(String context,int width,int height){
        BufferedImage qrCode=null;
        try {
            Hashtable hints= new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(context, BarcodeFormat.QR_CODE, width, height,hints);
            qrCode = MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException ex) {
            Logger.getLogger(ZxingTool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return qrCode;
    }
    
    /**
     * 生成帶有logo標誌的二維碼
     * @param context 二維碼儲存內容
     * @param width 二維碼寬度
     * @param height 二維碼高度
     * @param logoPath  二維碼logo路徑
     * @return 
     */
    public static BufferedImage encodeLogoQRcode(String context,int width,int height,String logoPath){
         BufferedImage logoQRcode=null;
        try {
             // 讀取Logo影象  
            BufferedImage logoImage = scale(logoPath, IMAGE_WIDTH,IMAGE_HEIGHT, true);  
            int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];  
            for (int i = 0; i < logoImage.getWidth(); i++) {  
                for (int j = 0; j < logoImage.getHeight(); j++) {  
                    srcPixels[i][j] = logoImage.getRGB(i, j);  
                }  
            }
            
            Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();  
            hint.put(EncodeHintType.CHARACTER_SET, "utf-8");  
            hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
           
            BitMatrix bitMatrix = new MultiFormatWriter().encode(context, BarcodeFormat.QR_CODE, width, height,hint);
            
             // 二維矩陣轉為一維畫素陣列  
             int halfW = bitMatrix.getWidth() / 2;  
             int halfH = bitMatrix.getHeight() / 2;
             
             int[] pixels = new int[width * height];  
  
             for (int y = 0; y < bitMatrix.getHeight(); y++) {  
                    for (int x = 0; x < bitMatrix.getWidth(); x++) {  
                        // 讀取圖片  
                        if (x > halfW - IMAGE_HALF_WIDTH  
                                && x < halfW + IMAGE_HALF_WIDTH  
                                && y > halfH - IMAGE_HALF_WIDTH  
                                && y < halfH + IMAGE_HALF_WIDTH) {  
                            pixels[y * width + x] = srcPixels[x - halfW  
                                    + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];  
                        }   
                        // 在圖片四周形成邊框  
                        else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)  
                                || (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                        && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                        && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                        + IMAGE_HALF_WIDTH + FRAME_WIDTH)  
                                || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                        && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                        && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                        - IMAGE_HALF_WIDTH + FRAME_WIDTH)  
                                || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                        && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                        && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                        + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {  
                            pixels[y * width + x] = 0xfffffff;  
                        } else {  
                            // 此處可以修改二維碼的顏色,可以分別制定二維碼和背景的顏色;  
                            pixels[y * width + x] = bitMatrix.get(x, y) ? 0xff000000 : 0xfffffff;  
                        }
                }  
            }
            logoQRcode = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
            logoQRcode.getRaster().setDataElements(0, 0, width, height, pixels);              
        } catch (WriterException ex) {
            Logger.getLogger(ZxingTool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return logoQRcode;
    }
    
    /**
     * 解析讀取二維碼
     * @param qrCodePath 二維碼圖片路徑
     * @return 
     */
    public static String decodeQRcode(String qrCodePath){
     BufferedImage image;  
     String qrCodeText = null;
        try {  
            image = ImageIO.read(new File(qrCodePath));  
            LuminanceSource source = new BufferedImageLuminanceSource(image);  
            Binarizer binarizer = new HybridBinarizer(source);  
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);  
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();  
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            // 對影象進行解碼
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);  
            qrCodeText = result.getText();
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (NotFoundException e) {  
            e.printStackTrace();  
        }  
        return qrCodeText;
    }
    
    /**
     * 對圖片進行縮放
     * @param imgPath 圖片路徑
     * @param width 圖片縮放後的寬度
     * @param height 圖片縮放後的高度
     * @param hasFiller 是否補白
     * @return 
     */
    public static BufferedImage scale(String imgPath,int width,int height,boolean hasFiller){
        double ratio = 0.0; // 縮放比例  
        File file = new File(imgPath);  
        BufferedImage srcImage = null;  
        try {
            srcImage = ImageIO.read(file);
        } catch (IOException ex) {
            Logger.getLogger(ZxingTool.class.getName()).log(Level.SEVERE, null, ex);
        }
        Image finalImage;  
        finalImage = srcImage.getScaledInstance(width, height,BufferedImage.SCALE_SMOOTH);
        // 計算比例  
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {  
            if (srcImage.getHeight() > srcImage.getWidth()) {  
                ratio = (new Integer(height)).doubleValue()/ srcImage.getHeight();  
            } else {  
                ratio = (new Integer(width)).doubleValue()/ srcImage.getWidth();  
            }  
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);  
            finalImage = op.filter(srcImage, null);  
        }  
        if (hasFiller) {// 補白  
            BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
            Graphics2D graphic = image.createGraphics();  
            graphic.setColor(Color.white);  
            graphic.fillRect(0, 0, width, height);  
            if (width == finalImage.getWidth(null)){  
                graphic.drawImage(finalImage, 0,(height - finalImage.getHeight(null))/2,finalImage.getWidth(null), finalImage.getHeight(null),Color.white, null);  
            }else{  
                graphic.drawImage(finalImage,(width - finalImage.getWidth(null))/2,0,finalImage.getWidth(null), finalImage.getHeight(null),Color.white, null);  
                graphic.dispose();  
                finalImage = image;  
            }
        }  
        return (BufferedImage) finalImage;
    }
}