二维码生成

(2)微信公众号二维码生成

pom.xml

<!-- 微信公众号 -->
<dependency>
   <groupId>com.github.binarywang</groupId>
   <artifactId>weixin-java-mp</artifactId>
</dependency>
<!-- 条形码、二维码生成  -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
</dependency>
package com.qike.api.util;

import cn.hutool.core.util.IdUtil;
import com.github.binarywang.utils.qrcode.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.qike.utils.qiniu.QiNiuYunUploadUtils;

import java.awt.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName QrCodeUtil
 * @Description 二维码生成
 */
public class QrCodeUtil {

    /**
     * width:图片完整的宽;height:图片完整的高
     */
    private static final int WIDTH = 205;
    /**
     * 二维码图片高度
     */
    private static final int HEIGHT = 205;


    /**
     * @param url 二维码中的地址
     */
    public static String generateQrcode(String url) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, Comparable> hints = new HashMap<>(16);
            // 设置UTF-8, 防止中文乱码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 设置二维码四周白色区域的大小
            hints.put(EncodeHintType.MARGIN, 1);
            // 设置二维码的容错性
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
            BitMatrix bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 开始画二维码 存放在本地路径
            MatrixToImageWriter.writeToStream(bitMatrix, "jpg", os);
//            return QiNiuYunUploadUtils.upload2QiNiu(os.toByteArray(), "qrcode");

            Map<String,String> pathInfo = ImageUtils.writeToLocal(os);
            return pathInfo.get("localHttpFilePath");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }



    /**
     * @param url 创建二维码+文字中的地址
     */

    public static String generateVerificationQrcode(String url,String verificationCode) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, Comparable> hints = new HashMap<>(16);
            // 设置UTF-8, 防止中文乱码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 设置二维码四周白色区域的大小
            hints.put(EncodeHintType.MARGIN, 1);
            // 设置二维码的容错性
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
            BitMatrix bitMatrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 开始画二维码 存放在本地路径
            MatrixToImageWriter.writeToStream(bitMatrix, "jpg", os);
            // 生成本地地址
            Map<String,String> pathInfo = ImageUtils.writeToLocal(os);

            // 合成二维码 二维码+code
            ByteArrayOutputStream byteArrayOutputStream = ImageUtils.pressText(verificationCode, new File(pathInfo.get("localFilePath")), Font.PLAIN , Color.black, 16);
            // 删除本地暂存图片文件
            File file = new File(pathInfo.get("localFilePath"));
            file.delete();

            Map<String,String> deviceQrCode = null;

            // 生成本地地址
             deviceQrCode = ImageUtils.writeToLocal(byteArrayOutputStream);
//                deviceQrCode = QiNiuYunUploadUtils.upload2QiNiu(byteArrayOutputStream.toByteArray(), "QrCode.jpg");
            return deviceQrCode.get("localHttpFilePath");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


}
package com.qike.api.util;

import cn.hutool.core.util.IdUtil;
import com.qike.api.exception.GlobalRuntimeException;
import com.qike.common.exception.Asserts;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ImageUtils {

    /**
     * 二维码暂时存放地址
     */
    private static String fileUploadPath = "/usr/local/tomcat/webapps/upload/";

    private static String fileUploadUrl = "http://。。。";

    /**
     * @param pressText 文字
     * @param file      需要添加文字的图片
     * @param fontStyle 字体样式
     * @param color     字体颜色
     * @param fontSize  字体大小
     * @为图片添加文字
     */
    public static ByteArrayOutputStream pressText(String pressText, File file, int fontStyle, Color color, int fontSize) {

        try {
            Image src = ImageIO.read(file);
            // 获取图片的宽高
            int width = src.getWidth(null);
            int imageH = src.getHeight(null);

            int PIC_HEIGHT = imageH + 60;

            BufferedImage image = new BufferedImage(width, PIC_HEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, PIC_HEIGHT);//填充整个屏幕
            g.drawImage(src, 0, 0, width, imageH, null);
            g.setColor(color);
            //设置字体
            Font font = new Font(null, fontStyle, fontSize);
            FontMetrics metrics = g.getFontMetrics(font);
            // 文字在图片中的坐标 这里设置在中间
            int startX = (width - metrics.stringWidth(pressText)) / 2;
            int startY = imageH + (60) / 2;
            g.setFont(font);
            g.drawString(pressText, startX, startY);
            g.dispose();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "JPEG", os);
            return os;

        } catch (Exception e) {
            System.out.println(e);
            Asserts.fail("二维码文字生成失败");
            throw new GlobalRuntimeException(300, "二维码文字生成失败");
        }
    }


    /**
     * 将InputStream写入本地文件
     *
     * @param os 输入流
     * @throws IOException IOException
     */
    public static Map<String,String> writeToLocal(ByteArrayOutputStream os){

        Map<String,String> pathInfo = null;
        FileOutputStream fileOutputStream = null;
        String fileName = IdUtil.simpleUUID() + ".jpg";
        String day = "";
        try {
            day=  DateFormatUtils.format(new Date(),"yyyyMMdd");

            File realPathDirectory = new File(fileUploadPath +day+"/");

            if (realPathDirectory == null || !realPathDirectory.exists()) {
                realPathDirectory.mkdirs();
            }

            fileOutputStream = new FileOutputStream(fileUploadPath +day+"/" + fileName);
            fileOutputStream.write(os.toByteArray());


        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        pathInfo=new HashMap<String,String>();
        pathInfo.put("localFilePath", fileUploadPath +day+"/"+ fileName);
        pathInfo.put("localHttpFilePath", fileUploadUrl +day+"/" + fileName);
        return  pathInfo;
    }


    /**
     * 判断文件夹是否存在,如果不存在则新建
     *
     * @param dirPath 文件夹路径
     */
    private static void isChartPathExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}

(2)微信小程序二维码生成

/**
     * 生成用户二维码
     *
     * @param userId 用户id
     * @return
     */
    private String generateQrCode(String userId) throws FileNotFoundException {
        // 生成小程序码
        final WxMaService wxService = WxMaConfiguration.getMaService(appId);
        File file = null;
        try {
            file = wxService.getQrcodeService().createWxaCodeUnlimit(userId, "pages/login/login");
        } catch (WxErrorException e) {
            e.printStackTrace();
            Asserts.fail("用户二维码生成失败");
        }

        MultipartFile multipartFile = null;
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            multipartFile = new MockMultipartFile("file" + file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ImageUploadUtil.imageUpload(userId+"qrCode.jpg", multipartFile, null);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值