生成、读取 二维码(QR码)-采用ZXing(已解决中文乱码的问题)

时间:2023-02-05 10:40:27

由maven构建项目,需要引入两个包,配置代码如下:

<dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>2.1</version>
    </dependency>

    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>2.1</version>
    </dependency>


代码如下:

  1 package qrcode;
  2  
  3 import java.awt.image.BufferedImage;
  4 import java.io.File;
  5 import java.io.IOException;
  6 import java.util.Hashtable;
  7 import java.util.Map;
  8 
  9 import javax.imageio.ImageIO;
 10 
 11 import com.google.zxing.BarcodeFormat;
 12 import com.google.zxing.BinaryBitmap;
 13 import com.google.zxing.DecodeHintType;
 14 import com.google.zxing.EncodeHintType;
 15 import com.google.zxing.LuminanceSource;
 16 import com.google.zxing.MultiFormatReader;
 17 import com.google.zxing.MultiFormatWriter;
 18 import com.google.zxing.ReaderException;
 19 import com.google.zxing.Result;
 20 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
 21 import com.google.zxing.common.BitMatrix;
 22 import com.google.zxing.common.HybridBinarizer;
 23  
 24  /**
 25   * 利用zxing开源工具生成二维码QRCode
 26   * 
 27   * @date 2013-04-11
 28   * @author lxl
 29   * 
 30   */
 31  public class QRCode {
 32      private static final int BLACK = 0xff000000;
 33      private static final int WHITE = 0xFFFFFFFF;
 34  
 35      /**
 36       * @param args
 37       */
 38      public static void main(String[] args) {
 39          QRCode test = new QRCode();
 40          File file = new File("C://test.png");
 41          /**
 42           * 在com.google.zxing.MultiFormatWriter类中,定义了一些我们不知道的码,二维码只是其中的一种<br>
 43           * public BitMatrix encode(String contents,
 44                            BarcodeFormat format,
 45                            int width, int height,
 46                            Map<EncodeHintType,?> hints) throws WriterException {
 47              Writer writer;
 48              switch (format) {
 49                case EAN_8:
 50                  writer = new EAN8Writer();
 51                  break;
 52                case EAN_13:
 53                  writer = new EAN13Writer();
 54                  break;
 55                case UPC_A:
 56                  writer = new UPCAWriter();
 57                  break;
 58                case QR_CODE:  //这里是二维码
 59                  writer = new QRCodeWriter();
 60                  break;
 61                case CODE_39:
 62                  writer = new Code39Writer();
 63                  break;
 64                case CODE_128:  //这个可以生成
 65                  writer = new Code128Writer();
 66                  break;
 67                case ITF:
 68                  writer = new ITFWriter();
 69                  break;
 70                case PDF_417:  //这个可以生成
 71                  writer = new PDF417Writer();
 72                  break;
 73                case CODABAR:
 74                  writer = new CodaBarWriter();
 75                  break;
 76                default:
 77                  throw new IllegalArgumentException("No encoder available for format " + format);
 78              }
 79              return writer.encode(contents, format, width, height, hints);
 80            }
 81  
 82           */
 83          test.encode("中文二维码信息", file, BarcodeFormat.QR_CODE, 200, 200, null);
 84          test.decode(file);
 85      }
 86  
 87      /**
 88       * 生成QRCode二维码<br> 
 89       * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>
 90       *  static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>
 91       *  修改为UTF-8,否则中文编译后解析不了<br>
 92       */
 93      public void encode(String contents, File file, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {
 94          try {
 95              contents=new String(contents.getBytes("UTF-8"),"ISO-8859-1");//如果不想更改源码,则将字符串转换成ISO-8859-1编码
 96              
 97              BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);
 98              writeToFile(bitMatrix, "png", file);
 99          } catch (Exception e) {
100              e.printStackTrace();
101          }
102      }
103  
104      /**
105       * 生成二维码图片<br>
106       * 
107       * @param matrix
108       * @param format
109       *            图片格式
110       * @param file
111       *            生成二维码图片位置
112       * @throws IOException
113       */
114      public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
115          BufferedImage image = toBufferedImage(matrix);
116          ImageIO.write(image, format, file);
117      }
118  
119      /**
120       * 生成二维码内容<br>
121       * 
122       * @param matrix
123       * @return
124       */
125      public static BufferedImage toBufferedImage(BitMatrix matrix) {
126          int width = matrix.getWidth();
127          int height = matrix.getHeight();
128          BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
129          for (int x = 0; x < width; x++) {
130              for (int y = 0; y < height; y++) {
131                  image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
132              }
133          }
134          return image;
135      }
136  
137      /**
138       * 解析QRCode二维码
139       */
140      @SuppressWarnings("unchecked")
141      public void decode(File file) {
142          try {
143              BufferedImage image;
144              try {
145                  image = ImageIO.read(file);
146                  if (image == null) {
147                      System.out.println("Could not decode image");
148                  }
149                  LuminanceSource source = new BufferedImageLuminanceSource(image);
150                  BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
151                  Result result;
152                  @SuppressWarnings("rawtypes")
153                  Hashtable hints = new Hashtable();
154                  //解码设置编码方式为:utf-8
155                  hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
156                  result = new MultiFormatReader().decode(bitmap, hints);
157                  String resultStr = result.getText();
158                  System.out.println("解析后内容:" + resultStr);
159              } catch (IOException ioe) {
160                  System.out.println(ioe.toString());
161              } catch (ReaderException re) {
162                  System.out.println(re.toString());
163              }
164          } catch (Exception ex) {
165              System.out.println(ex.toString());
166          }
167      }
168  }