zoukankan      html  css  js  c++  java
  • java利用zxing编码解码一维码与二维码

      最近琢磨了一下二维码、一维码的编码、解码方法,感觉google的zxing用起来还是比较方便。 
      本人原创,欢迎转载,转载请标注原文地址:http://wallimn.iteye.com/blog/2071020 
    
    一、工具类 
    Java代码  收藏代码
    package com.exam.services.qrcode;  
      
    import com.google.zxing.BarcodeFormat;  
    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.Result;  
    import com.google.zxing.WriterException;  
    import com.google.zxing.client.j2se.BufferedImageLuminanceSource;  
    import com.google.zxing.common.BitMatrix;  
    import com.google.zxing.common.HybridBinarizer;  
      
    import javax.imageio.ImageIO;  
      
    import java.io.File;  
    import java.io.OutputStream;  
    import java.io.IOException;  
    import java.util.Hashtable;  
    import java.awt.image.BufferedImage;  
      
    /** 
     * 使用ZXing2.3,生成条码的辅助类。可以编码、解码。编码使用code包,解码需要javase包。 
     *  
     * <br/> 
     * <br/> 
     * 作者:wallimn<br/> 
     * 联系:54871876@qq.com,http://wallimn.iteye.com<br/> 
     * 时间:2014年5月25日  下午10:33:05<br/> 
     */  
    public final class MatrixUtil {  
      
        private static final String CHARSET = "utf-8";  
        private static final int BLACK = 0xFF000000;  
        private static final int WHITE = 0xFFFFFFFF;  
      
        /** 
         * 禁止生成实例,生成实例也没有意义。 
         */  
        private MatrixUtil() {  
        }  
      
        /** 
         * 生成矩阵,是一个简单的函数,参数固定,更多的是使用示范。 
         *  
         * <br/> 
         * <br/> 
         * 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:41:12<br/> 
         * 联系:54871876@qq.com<br/> 
         *  
         * @param text 
         * @return 
         */  
        public static BitMatrix toQRCodeMatrix(String text, Integer width,  
                Integer height) {  
            if (width == null || width < 300) {  
                width = 300;  
            }  
      
            if (height == null || height < 300) {  
                height = 300;  
            }  
            // 二维码的图片格式  
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
            // 内容所使用编码  
            hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
            BitMatrix bitMatrix = null;  
            try {  
                bitMatrix = new MultiFormatWriter().encode(text,  
                        BarcodeFormat.QR_CODE, width, height, hints);  
            } catch (WriterException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            // 生成二维码  
            // File outputFile = new File("d:"+File.separator+"new.gif");  
            // MatrixUtil.writeToFile(bitMatrix, format, outputFile);  
            return bitMatrix;  
        }  
      
        /** 
         * 将指定的字符串生成二维码图片。简单的使用示例。 
         *  
         * <br/> 
         * <br/> 
         * 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:44:52<br/> 
         * 联系:54871876@qq.com<br/> 
         *  
         * @param text 
         * @param file 
         * @param format 
         * @return 
         */  
        public boolean toQrcodeFile(String text, File file, String format) {  
            BitMatrix matrix = toQRCodeMatrix(text, null, null);  
            if (matrix != null) {  
                try {  
                    writeToFile(matrix, format, file);  
                    return true;  
                } catch (IOException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
            }  
            return false;  
        }  
      
        /** 
         * 根据点矩阵生成黑白图。 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:26:22<br/> 
         * 联系:54871876@qq.com<br/> 
         */  
        public static BufferedImage toBufferedImage(BitMatrix matrix) {  
            int width = matrix.getWidth();  
            int height = matrix.getHeight();  
            BufferedImage image = new BufferedImage(width, height,  
                    BufferedImage.TYPE_INT_RGB);  
            for (int x = 0; x < width; x++) {  
                for (int y = 0; y < height; y++) {  
                    image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
                }  
            }  
            return image;  
        }  
      
        /** 
         * 将字符串编成一维条码的矩阵 
         *  
         * <br/> 
         * <br/> 
         * 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:56:34<br/> 
         * 联系:54871876@qq.com<br/> 
         *  
         * @param str 
         * @param width 
         * @param height 
         * @return 
         */  
        public static BitMatrix toBarCodeMatrix(String str, Integer width,  
                Integer height) {  
      
            if (width == null || width < 200) {  
                width = 200;  
            }  
      
            if (height == null || height < 50) {  
                height = 50;  
            }  
      
            try {  
                // 文字编码  
                Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
                hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
      
                BitMatrix bitMatrix = new MultiFormatWriter().encode(str,  
                        BarcodeFormat.CODE_128, width, height, hints);  
      
                return bitMatrix;  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return null;  
        }  
      
        /** 
         * 根据矩阵、图片格式,生成文件。 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:26:43<br/> 
         * 联系:54871876@qq.com<br/> 
         */  
        public static void writeToFile(BitMatrix matrix, String format, File file)  
                throws IOException {  
            BufferedImage image = toBufferedImage(matrix);  
            if (!ImageIO.write(image, format, file)) {  
                throw new IOException("Could not write an image of format "  
                        + format + " to " + file);  
            }  
        }  
      
        /** 
         * 将矩阵写入到输出流中。 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:27:58<br/> 
         * 联系:54871876@qq.com<br/> 
         */  
        public static void writeToStream(BitMatrix matrix, String format,  
                OutputStream stream) throws IOException {  
            BufferedImage image = toBufferedImage(matrix);  
            if (!ImageIO.write(image, format, stream)) {  
                throw new IOException("Could not write an image of format "  
                        + format);  
            }  
        }  
      
        /** 
         * 解码,需要javase包。 
         *  
         * <br/> 
         * <br/> 
         * 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午11:06:07<br/> 
         * 联系:54871876@qq.com<br/> 
         *  
         * @param file 
         * @return 
         */  
        public static String decode(File file) {  
      
            BufferedImage image;  
            try {  
                if (file == null || file.exists() == false) {  
                    throw new Exception(" File not found:" + file.getPath());  
                }  
      
                image = ImageIO.read(file);  
      
                LuminanceSource source = new BufferedImageLuminanceSource(image);  
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
      
                Result result;  
      
                // 解码设置编码方式为:utf-8,  
                Hashtable hints = new Hashtable();  
                hints.put(DecodeHintType.CHARACTER_SET, CHARSET);  
      
                result = new MultiFormatReader().decode(bitmap, hints);  
      
                return result.getText();  
      
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
      
            return null;  
        }  
    }  
    
    
    二、使用示例 
    Java代码  收藏代码
    package com.exam.services.qrcode;  
      
      
    import java.io.File;  
        
    public class Test {    
        
        /** 
         * 测试函数。简单地将指定的字符串生成二维码图片。   
         *  
         * <br/><br/> 
         * 作者:wallimn<br/> 
         * 时间:2014年5月25日  下午10:30:00<br/> 
         * 联系:54871876@qq.com<br/> 
         */  
        public static void main(String[] args) throws Exception {    
            String text = "http://wallimn.itey.com";    
            String result;  
            String format = "gif";    
            //生成二维码    
            File outputFile = new File("d:"+File.separator+"rqcode.gif");    
            MatrixUtil.writeToFile(MatrixUtil.toQRCodeMatrix(text, null, null), format, outputFile);    
            result = MatrixUtil.decode(outputFile);  
            System.out.println(result);  
              
            outputFile = new File("d:"+File.separator+"barcode.gif");    
            MatrixUtil.writeToFile(MatrixUtil.toBarCodeMatrix(text, null, null), format, outputFile);  
        
            result = MatrixUtil.decode(outputFile);  
            System.out.println(result);  
        }    
        
    }    
    

      

      最近琢磨了一下二维码、一维码的编码、解码方法,感觉google的zxing用起来还是比较方便。 
      本人原创,欢迎转载,转载请标注原文地址:http://wallimn.iteye.com/blog/2071020 

    一、工具类 

    Java代码  收藏代码
    1. package com.exam.services.qrcode;  
    2.   
    3. import com.google.zxing.BarcodeFormat;  
    4. import com.google.zxing.BinaryBitmap;  
    5. import com.google.zxing.DecodeHintType;  
    6. import com.google.zxing.EncodeHintType;  
    7. import com.google.zxing.LuminanceSource;  
    8. import com.google.zxing.MultiFormatReader;  
    9. import com.google.zxing.MultiFormatWriter;  
    10. import com.google.zxing.Result;  
    11. import com.google.zxing.WriterException;  
    12. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;  
    13. import com.google.zxing.common.BitMatrix;  
    14. import com.google.zxing.common.HybridBinarizer;  
    15.   
    16. import javax.imageio.ImageIO;  
    17.   
    18. import java.io.File;  
    19. import java.io.OutputStream;  
    20. import java.io.IOException;  
    21. import java.util.Hashtable;  
    22. import java.awt.image.BufferedImage;  
    23.   
    24. /** 
    25.  * 使用ZXing2.3,生成条码的辅助类。可以编码、解码。编码使用code包,解码需要javase包。 
    26.  *  
    27.  * <br/> 
    28.  * <br/> 
    29.  * 作者:wallimn<br/> 
    30.  * 联系:54871876@qq.com,http://wallimn.iteye.com<br/> 
    31.  * 时间:2014年5月25日  下午10:33:05<br/> 
    32.  */  
    33. public final class MatrixUtil {  
    34.   
    35.     private static final String CHARSET = "utf-8";  
    36.     private static final int BLACK = 0xFF000000;  
    37.     private static final int WHITE = 0xFFFFFFFF;  
    38.   
    39.     /** 
    40.      * 禁止生成实例,生成实例也没有意义。 
    41.      */  
    42.     private MatrixUtil() {  
    43.     }  
    44.   
    45.     /** 
    46.      * 生成矩阵,是一个简单的函数,参数固定,更多的是使用示范。 
    47.      *  
    48.      * <br/> 
    49.      * <br/> 
    50.      * 作者:wallimn<br/> 
    51.      * 时间:2014年5月25日  下午10:41:12<br/> 
    52.      * 联系:54871876@qq.com<br/> 
    53.      *  
    54.      * @param text 
    55.      * @return 
    56.      */  
    57.     public static BitMatrix toQRCodeMatrix(String text, Integer width,  
    58.             Integer height) {  
    59.         if (width == null || width < 300) {  
    60.             width = 300;  
    61.         }  
    62.   
    63.         if (height == null || height < 300) {  
    64.             height = 300;  
    65.         }  
    66.         // 二维码的图片格式  
    67.         Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
    68.         // 内容所使用编码  
    69.         hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
    70.         BitMatrix bitMatrix = null;  
    71.         try {  
    72.             bitMatrix = new MultiFormatWriter().encode(text,  
    73.                     BarcodeFormat.QR_CODE, width, height, hints);  
    74.         } catch (WriterException e) {  
    75.             // TODO Auto-generated catch block  
    76.             e.printStackTrace();  
    77.         }  
    78.         // 生成二维码  
    79.         // File outputFile = new File("d:"+File.separator+"new.gif");  
    80.         // MatrixUtil.writeToFile(bitMatrix, format, outputFile);  
    81.         return bitMatrix;  
    82.     }  
    83.   
    84.     /** 
    85.      * 将指定的字符串生成二维码图片。简单的使用示例。 
    86.      *  
    87.      * <br/> 
    88.      * <br/> 
    89.      * 作者:wallimn<br/> 
    90.      * 时间:2014年5月25日  下午10:44:52<br/> 
    91.      * 联系:54871876@qq.com<br/> 
    92.      *  
    93.      * @param text 
    94.      * @param file 
    95.      * @param format 
    96.      * @return 
    97.      */  
    98.     public boolean toQrcodeFile(String text, File file, String format) {  
    99.         BitMatrix matrix = toQRCodeMatrix(text, nullnull);  
    100.         if (matrix != null) {  
    101.             try {  
    102.                 writeToFile(matrix, format, file);  
    103.                 return true;  
    104.             } catch (IOException e) {  
    105.                 // TODO Auto-generated catch block  
    106.                 e.printStackTrace();  
    107.             }  
    108.         }  
    109.         return false;  
    110.     }  
    111.   
    112.     /** 
    113.      * 根据点矩阵生成黑白图。 作者:wallimn<br/> 
    114.      * 时间:2014年5月25日  下午10:26:22<br/> 
    115.      * 联系:54871876@qq.com<br/> 
    116.      */  
    117.     public static BufferedImage toBufferedImage(BitMatrix matrix) {  
    118.         int width = matrix.getWidth();  
    119.         int height = matrix.getHeight();  
    120.         BufferedImage image = new BufferedImage(width, height,  
    121.                 BufferedImage.TYPE_INT_RGB);  
    122.         for (int x = 0; x < width; x++) {  
    123.             for (int y = 0; y < height; y++) {  
    124.                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
    125.             }  
    126.         }  
    127.         return image;  
    128.     }  
    129.   
    130.     /** 
    131.      * 将字符串编成一维条码的矩阵 
    132.      *  
    133.      * <br/> 
    134.      * <br/> 
    135.      * 作者:wallimn<br/> 
    136.      * 时间:2014年5月25日  下午10:56:34<br/> 
    137.      * 联系:54871876@qq.com<br/> 
    138.      *  
    139.      * @param str 
    140.      * @param width 
    141.      * @param height 
    142.      * @return 
    143.      */  
    144.     public static BitMatrix toBarCodeMatrix(String str, Integer width,  
    145.             Integer height) {  
    146.   
    147.         if (width == null || width < 200) {  
    148.             width = 200;  
    149.         }  
    150.   
    151.         if (height == null || height < 50) {  
    152.             height = 50;  
    153.         }  
    154.   
    155.         try {  
    156.             // 文字编码  
    157.             Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
    158.             hints.put(EncodeHintType.CHARACTER_SET, CHARSET);  
    159.   
    160.             BitMatrix bitMatrix = new MultiFormatWriter().encode(str,  
    161.                     BarcodeFormat.CODE_128, width, height, hints);  
    162.   
    163.             return bitMatrix;  
    164.         } catch (Exception e) {  
    165.             e.printStackTrace();  
    166.         }  
    167.         return null;  
    168.     }  
    169.   
    170.     /** 
    171.      * 根据矩阵、图片格式,生成文件。 作者:wallimn<br/> 
    172.      * 时间:2014年5月25日  下午10:26:43<br/> 
    173.      * 联系:54871876@qq.com<br/> 
    174.      */  
    175.     public static void writeToFile(BitMatrix matrix, String format, File file)  
    176.             throws IOException {  
    177.         BufferedImage image = toBufferedImage(matrix);  
    178.         if (!ImageIO.write(image, format, file)) {  
    179.             throw new IOException("Could not write an image of format "  
    180.                     + format + " to " + file);  
    181.         }  
    182.     }  
    183.   
    184.     /** 
    185.      * 将矩阵写入到输出流中。 作者:wallimn<br/> 
    186.      * 时间:2014年5月25日  下午10:27:58<br/> 
    187.      * 联系:54871876@qq.com<br/> 
    188.      */  
    189.     public static void writeToStream(BitMatrix matrix, String format,  
    190.             OutputStream stream) throws IOException {  
    191.         BufferedImage image = toBufferedImage(matrix);  
    192.         if (!ImageIO.write(image, format, stream)) {  
    193.             throw new IOException("Could not write an image of format "  
    194.                     + format);  
    195.         }  
    196.     }  
    197.   
    198.     /** 
    199.      * 解码,需要javase包。 
    200.      *  
    201.      * <br/> 
    202.      * <br/> 
    203.      * 作者:wallimn<br/> 
    204.      * 时间:2014年5月25日  下午11:06:07<br/> 
    205.      * 联系:54871876@qq.com<br/> 
    206.      *  
    207.      * @param file 
    208.      * @return 
    209.      */  
    210.     public static String decode(File file) {  
    211.   
    212.         BufferedImage image;  
    213.         try {  
    214.             if (file == null || file.exists() == false) {  
    215.                 throw new Exception(" File not found:" + file.getPath());  
    216.             }  
    217.   
    218.             image = ImageIO.read(file);  
    219.   
    220.             LuminanceSource source = new BufferedImageLuminanceSource(image);  
    221.             BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
    222.   
    223.             Result result;  
    224.   
    225.             // 解码设置编码方式为:utf-8,  
    226.             Hashtable hints = new Hashtable();  
    227.             hints.put(DecodeHintType.CHARACTER_SET, CHARSET);  
    228.   
    229.             result = new MultiFormatReader().decode(bitmap, hints);  
    230.   
    231.             return result.getText();  
    232.   
    233.         } catch (Exception e) {  
    234.             e.printStackTrace();  
    235.         }  
    236.   
    237.         return null;  
    238.     }  
    239. }  



    二、使用示例 

    Java代码  收藏代码
    1. package com.exam.services.qrcode;  
    2.   
    3.   
    4. import java.io.File;  
    5.     
    6. public class Test {    
    7.     
    8.     /** 
    9.      * 测试函数。简单地将指定的字符串生成二维码图片。   
    10.      *  
    11.      * <br/><br/> 
    12.      * 作者:wallimn<br/> 
    13.      * 时间:2014年5月25日  下午10:30:00<br/> 
    14.      * 联系:54871876@qq.com<br/> 
    15.      */  
    16.     public static void main(String[] args) throws Exception {    
    17.         String text = "http://wallimn.itey.com";    
    18.         String result;  
    19.         String format = "gif";    
    20.         //生成二维码    
    21.         File outputFile = new File("d:"+File.separator+"rqcode.gif");    
    22.         MatrixUtil.writeToFile(MatrixUtil.toQRCodeMatrix(text, nullnull), format, outputFile);    
    23.         result = MatrixUtil.decode(outputFile);  
    24.         System.out.println(result);  
    25.           
    26.         outputFile = new File("d:"+File.separator+"barcode.gif");    
    27.         MatrixUtil.writeToFile(MatrixUtil.toBarCodeMatrix(text, nullnull), format, outputFile);  
    28.     
    29.         result = MatrixUtil.decode(outputFile);  
    30.         System.out.println(result);  
    31.     }    
    32.     
    33. }    
  • 相关阅读:
    【题解】【BT】【Leetcode】Populating Next Right Pointers in Each Node
    【题解】【BT】【Leetcode】Binary Tree Level Order Traversal
    【题解】【BST】【Leetcode】Unique Binary Search Trees
    【题解】【矩阵】【回溯】【Leetcode】Rotate Image
    【题解】【排列组合】【素数】【Leetcode】Unique Paths
    【题解】【矩阵】【回溯】【Leetcode】Unique Paths II
    【题解】【BST】【Leetcode】Validate Binary Search Tree
    【题解】【BST】【Leetcode】Convert Sorted Array to Binary Search Tree
    第 10 章 判断用户是否登录
    第 8 章 动态管理资源结合自定义登录页面
  • 原文地址:https://www.cnblogs.com/ruiati/p/5757407.html
Copyright © 2011-2022 走看看