生成一维码与解析一维码

  • Post author:
  • Post category:其他




maven引入

<!-- 一维码或二维码编码 -->
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.2.0</version>
</dependency>

<!-- 一维码或二维码解码 -->
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>3.2.0</version>
</dependency>



生成一维码

	/**
	* 一维码写入指定文件
	*/
	public static void writeToFile(String str, Integer width, Integer height, String format, File file) throws IOException {
        BitMatrix matrix = toBarCodeMatrix(str,width,height);
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

	/**
	* 一维码写入流中
	*/
    public static void writeToStream(String str, Integer width, Integer height, String format, OutputStream stream) throws IOException {
        BitMatrix matrix = toBarCodeMatrix(str,width,height);
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format "
                    + format);
        }
    }

	/**
	* 生成一维码
	*/
    public static BitMatrix toBarCodeMatrix(String str, Integer width, Integer height) {
        if (width == null || width <= 0) {
            width = 200;
        }
        if (height == null || height <= 0) {
            height = 50;
        }
        try {
            // 文字编码
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.CODE_128, width, height, hints);
            return bitMatrix;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



解析一维码

	/**
	*  解析一维码
	* @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, "utf-8");

            result = new MultiFormatReader().decode(bitmap, hints);

            return result.getText();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



版权声明:本文为burmem原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。