首页 > php教程 > php手册 > 正文

ZXing 二维码解析生成工具类

php中文网
发布: 2016-06-01 09:46:44
原创
2294人浏览过

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,Object>(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,Object> HINTS;
        private static final Map<DecodeHintType,Object> HINTS_PURE;
        static {
            HINTS = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
            HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
            HINTS_PURE = new EnumMap<DecodeHintType,Object>(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();
        }
    }
}
登录后复制

 

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号