正在用SpringBoot做生成解析二维码的看过来 仔细读一下代码基本问题都能解决

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。正在用SpringBoot做生成解析二维码的看过来 仔细读一下代码基本问题都能解决,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

首先是maven依赖

<!-- 二维码工具 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.2.1</version>
        </dependency>
        <!--hutool核心工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
@RestController
@RequestMapping("/marge")
@Slf4j
public class MargeController {
    private final static String CHARSET = "utf-8";

    @GetMapping("/index")
    public String test() {
        System.out.println("微信测试测试进来了");
        return "welcome";
    }

    @PostMapping("/mergeCheck")
    public Map mergeCheck(MultipartFile wxImg, MultipartFile aliImg, MultipartFile qqImg, String imgSource) throws Exception {
        if (wxImg != null && qqImg == null && aliImg == null) {
            HashMap<String, Object> map = getImg(wxImg, imgSource);
            return map;
        } else if (wxImg == null && qqImg != null && aliImg == null) {
            HashMap<String, Object> map = getImg(qqImg, imgSource);
            return map;
        } else{
            HashMap<String, Object> map = getImg(aliImg, imgSource);
            return map;
        }
    }

    private static HashMap<String, Object> getImg(MultipartFile file, String imgSource) throws Exception {
        @Cleanup
        InputStream fileInputStream = file.getInputStream();
        //通过传进来的文件获取搭配解析需要的参数
        LuminanceSource source = new BufferedImageLuminanceSource(ImageIO.read(fileInputStream));
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        // 对收款码进行解码
        Result imgresult = new MultiFormatReader().decode(binaryBitmap, hints);
        String imgText = imgresult.getText();
        System.out.println("二维码解码结果:==============》》》》" + imgText);
        if (imgSource.equals("101")) {
            System.out.println("微信二维码解码结果是否包含wxp:==============》》》》" + imgText.contains("wxp:"));
            if (!imgText.contains("wxp:")) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("error", "上传失败!请上传微信收款二维码");
                return map;
            }
        } else if (imgSource.equals("102")) {
            System.out.println("支付宝二维码解码结果是否包含alipay:==============》》》》" + imgText.contains("alipay"));
            if (!imgText.contains("alipay")) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("error", "上传失败!请上传支付宝收款二维码");
                return map;
            }
        } else if (imgSource.equals("103")) {
            System.out.println("qq二维码解码结果是否包含qianbao.qq:==============》》》》" + imgText.contains("qianbao.qq"));
            if (!imgText.contains("qianbao.qq")) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("error", "上传失败!请上传QQ收款二维码");
                return map;
            }
        }
        BufferedImage imageNoWhite = createImageNoWhite(imgText);
        Img qrcode = Img.from(imageNoWhite);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write((RenderedImage) qrcode.getImg(), "PNG", os);
        @Cleanup
        InputStream byteArrayInputStream = new ByteArrayInputStream(os.toByteArray());
        String uriPrefix = "data:image/jpeg;base64,";
        String str = uriPrefix + imageToBase64(byteArrayInputStream);
        HashMap<String, Object> map = new HashMap<>();
        map.put("content", imgText);
        map.put("mergeImg", str);


        @Cleanup
        InputStream byteArrayInputStream2 = new ByteArrayInputStream(os.toByteArray());
        QiniuOssUtils utils = new QiniuOssUtils();
        String test = utils.upload(byteArrayInputStream2,  System.currentTimeMillis()+".jpg");
        System.out.println(test);
        return map;
    }


    @GetMapping("/toMerge")
    public Map toMerge(String wxImgText, String aliImgText, String qqImgText) throws Exception {
        //这句代码是为了获取背景图片
        Img backgroundImg = Img.from(FileUtil.getInputStream(new File("C:\\Song\\img\\画板 9.png")));
        //拿到背景图片的尺寸
        int backgroundScale = Math.min(backgroundImg.getImg().getHeight(null), backgroundImg.getImg().getWidth(null));
        //生成支付宝二维码
        BufferedImage aliimageNoWhite = createImageNoWhite(aliImgText);
        //获取到支付宝二维码图片
        Img aliQrcode = Img.from(aliimageNoWhite);
        if (qqImgText != null && qqImgText != "") {
            System.out.println("三码合一===========================》》》》");
            BufferedImage qqimage = createImageNoWhite(qqImgText);
            Img qqQrcode = Img.from(qqimage);
            BufferedImage wximageNoWhite = createImageNoWhite(wxImgText);
            Img wxQrcode = Img.from(wximageNoWhite);
            //设置qq二维码缩放大小 基于背景的尺寸去设置微信二维码的尺寸
            int qqQrcodeScale = (int) (backgroundScale * .7);
            qqQrcode.scale(qqQrcodeScale, qqQrcodeScale);
            int aqsc = (int) (qqQrcodeScale / 3.2);
            aliQrcode.scale(aqsc, aqsc);
            wxQrcode.scale(aqsc, aqsc);
            //设置支付宝二维码的偏移量
            int aliQrcodexy = (int) (qqQrcodeScale / 4.4);
            backgroundImg
                    .pressImage(qqQrcode.getImg(), 0, 0, 1)
                    .pressImage(wxQrcode.getImg(), -aliQrcodexy, aliQrcodexy, 1)
                    .pressImage(aliQrcode.getImg(), aliQrcodexy, aliQrcodexy, 1);
            //backgroundImg.pressImage(qqQrcode.getImg(), 0, 0, 1);
        } else {
            System.out.println("二码合一===========================》》》》");
            //调用方法生成微信二维码
            BufferedImage wxImage = createImageNoWhite(wxImgText);
            Img wxQrcode = Img.from(wxImage);
            //设置微信二维码缩放大小 基于背景的尺寸去设置微信二维码的尺寸
            int wxQrcodeScale = (int) (backgroundScale * .7);
            wxQrcode.scale(wxQrcodeScale, wxQrcodeScale);
            int aqsc = (int) (wxQrcodeScale / 3.2);
            aliQrcode.scale(aqsc, aqsc);
            //设置支付宝二维码的偏移量
            int aliQrcodexy = (int) (wxQrcodeScale / 4.2);
            backgroundImg
                    .pressImage(wxQrcode.getImg(), 0, 0, 1)
                    .pressImage(aliQrcode.getImg(), aliQrcodexy, aliQrcodexy, 1);
        }
        //创建一个ByteArrayOutputStream
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write((RenderedImage) backgroundImg.getImg(), "PNG", os);
        //ByteArrayOutputStream转成InputStream
        QiniuOssUtils utils = new QiniuOssUtils();
        @Cleanup
        InputStream byteArrayInputStream = new ByteArrayInputStream(os.toByteArray());
        String test = utils.upload(byteArrayInputStream,  System.currentTimeMillis()+".jpg");
        HashMap<String, Object> map = new HashMap<>();
        map.put("qiniu", test);


        ByteArrayOutputStream os2 = new ByteArrayOutputStream();
        ImageIO.write((RenderedImage) backgroundImg.getImg(), "PNG", os2);
        @Cleanup
        InputStream byteArrayInputStream2 = new ByteArrayInputStream(os2.toByteArray());
        String uriPrefix = "data:image/jpeg;base64,";
        String str = uriPrefix + imageToBase64(byteArrayInputStream2);
        System.out.println("合并成功!!!==================》》》》》》》》》》》》"+str);
        map.put("mergeImg", str);
        System.out.println(test);



        return map;
    }




    //内容生成生成二维码
    private static BufferedImage createImage(String content) throws IOException {
        //等同于hashmap,hashtable是线程安全的
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        //高容错率二维码
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 250, 250, hints);
        } catch (WriterException e) {
            log.info("生成二维码信息异常,请稍后重试");
            throw new RuntimeException("The generated QR code information is abnormal, please try again later");
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        //直接返回生成的二维码
        return image;
    }


    private static BufferedImage createImageNoWhite(String content) throws IOException {
        //等同于hashmap,hashtable是线程安全的
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        //高容错率二维码
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 250, 250, hints);
            bitMatrix = deleteWhite(bitMatrix);
        } catch (WriterException e) {
            log.info("生成二维码信息异常,请稍后重试");
            throw new RuntimeException("The generated QR code information is abnormal, please try again later");
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        //直接返回生成的二维码
        return image;
    }

    //base64展示,可以直接在线显示合并内容
    public static String imageToBase64(InputStream in) {
        try {
            byte[] data = IoUtil.readBytes(in);
            return Base64.getEncoder().encodeToString(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //删除生成二维码多余的白边
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }
}

碰到一个坑就是后端返回给前端解析结果的时候没事 但是前端再原封不动的还给后端的时候会把中间一部分自动编码!!!!!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/188060.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!