Home php教程 php手册 ZXing 二维码解析生成工具类

ZXing 二维码解析生成工具类

Jun 01, 2016 am 09:46 AM
zxing QR code parse

<code class="language-java">import com.google.zxing.*;
import com.google.zxing.Reader;
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.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;
 
import javax.imageio.ImageIO;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.*;
 
/**
 * 二维码生成工具类
 *
 * @author KisChang
 * @version 1.0
 * @date 2015年12月03日
 * @since 1.0
 */
public class ZXingUtils {
 
    public static enum ImageType {
        JPEG("jpeg"),PNG("png"),GIF("gif");
        private String value;
 
        ImageType(String value) {
            this.value = value;
        }
 
        public String getValue() {
            return value;
        }
    }
 
    /**编码*/
    public static class Encode {
 
        private static Map<encodehinttype object> HINTS;
        static {
            HINTS = new EnumMap<encodehinttype>(EncodeHintType.class);
            HINTS.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        }
        /**
         * 生成二维码
         * @param widthAndHeight    高宽
         * @param content           二维码内容
         * @param os                输出流
         */
        public static void buildQRCode(int widthAndHeight, String content, OutputStream os, ImageType imageType) throws WriterException, IOException {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, HINTS);// 生成矩阵
            MatrixToImageWriter.writeToStream(bitMatrix, imageType.getValue(), os);
        }
 
        public static void buildQRCode(String content, OutputStream os, ImageType imageType) throws WriterException, IOException {
            buildQRCode(200, content, os, imageType);
        }
 
        /**
         * 生成二维码
         * @param widthAndHeight    高宽
         * @param content           二维码内容
         * @param filePath          输出目录
         * @param fileName          输出文件名
         * @param imageType         输出文件类型
         */
        public static void buildQRCode(int widthAndHeight, String content, String filePath, String fileName, ImageType imageType) throws WriterException, IOException {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, HINTS);
            Path path = FileSystems.getDefault().getPath(filePath, fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, imageType.getValue(), path);// 输出图像
        }
 
        public static void buildQRCode(String content, String filePath, String fileName, ImageType imageType) throws WriterException, IOException {
            buildQRCode(200, content,filePath,fileName,imageType);
        }
    }
 
 
    /**解码*/
    public static class Decode {
 
        private static final Map<decodehinttype> HINTS;
        private static final Map<decodehinttype> HINTS_PURE;
        static {
            HINTS = new EnumMap<decodehinttype>(DecodeHintType.class);
            HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
            HINTS_PURE = new EnumMap<decodehinttype>(HINTS);
            HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        }
 
        /**
         * 解析二维码
         */
        public static Collection<result> readQRCode(File qrCode) throws ReaderException, IOException {
            FileInputStream inputStream = new FileInputStream(qrCode);
            return readQRCode(inputStream);
        }
 
        public static Collection<result> readQRCode(InputStream inputStream) throws ReaderException, IOException {
            LuminanceSource source = new BufferedImageLuminanceSource(ImageIO.read(inputStream));
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
 
            Collection<result> results = new ArrayList<result>(1);
            ReaderException savedException = null;
            Reader reader = new MultiFormatReader();
            try {
                //寻找多个条码
                MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
                Result[] theResults = multiReader.decodeMultiple(binaryBitmap, HINTS);
                if (theResults != null) {
                    results.addAll(Arrays.asList(theResults));
                }
            } catch (ReaderException re) {
                savedException = re;
            }
 
            if (results.isEmpty()) {
                try {
                    //寻找纯条码
                    Result theResult = reader.decode(binaryBitmap, HINTS_PURE);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
 
            if (results.isEmpty()) {
                try {
                    //寻找图片中的正常条码
                    Result theResult = reader.decode(binaryBitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
 
            if (results.isEmpty()) {
                try {
                    //再次尝试其他特殊处理
                    BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Result theResult = reader.decode(hybridBitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }
            if (results.isEmpty()){
                throw savedException;
            }else {
                return results;
            }
        }
 
 
        public static Result readQRCodeResult(File qrCode) throws ReaderException, IOException {
            FileInputStream inputStream = new FileInputStream(qrCode);
            return readQRCodeResult(inputStream);
        }
        public static Result readQRCodeResult(InputStream inputStream) throws ReaderException, IOException {
            Collection<result> results = readQRCode(inputStream);
            if (!results.isEmpty()){
                //寻找结果集中非空的结果
                for (Result result : results){
                    if (result != null){
                        return result;
                    }
                }
            }
            throw NotFoundException.getNotFoundInstance();
        }
    }
}</result></result></result></result></result></decodehinttype></decodehinttype></decodehinttype></decodehinttype></encodehinttype></encodehinttype></code>
Copy after login

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A deep dive into the meaning and usage of HTTP status code 460 A deep dive into the meaning and usage of HTTP status code 460 Feb 18, 2024 pm 08:29 PM

A deep dive into the meaning and usage of HTTP status code 460

How to create a QR code using wps How to create a QR code using wps Mar 28, 2024 am 09:41 AM

How to create a QR code using wps

iBatis and MyBatis: Comparison and Advantage Analysis iBatis and MyBatis: Comparison and Advantage Analysis Feb 18, 2024 pm 01:53 PM

iBatis and MyBatis: Comparison and Advantage Analysis

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to Microsoft account

What should I do if the QR code on Enterprise WeChat cannot be loaded? What should I do if the QR code on Enterprise WeChat cannot be loaded? Mar 14, 2024 pm 10:46 PM

What should I do if the QR code on Enterprise WeChat cannot be loaded?

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

Analysis of the meaning and usage of midpoint in PHP

Apache2 cannot correctly parse PHP files Apache2 cannot correctly parse PHP files Mar 08, 2024 am 11:09 AM

Apache2 cannot correctly parse PHP files

See all articles