二维码生成

本文介绍了一个用于生成带Logo的二维码的Java类库,包括二维码的创建、插入Logo、以及通过不同方式输出二维码图像的方法。同时,提供了在Web应用中动态生成二维码流和导出二维码的控制器实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1。

 
 

public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 100;
    // LOGO高度
    private static final int HEIGHT = 100;
 
    /**
     * 生成二维码的方法
     *
     * @param content      目标URL
     * @param imgPath      LOGO图片地址
     * @param needCompress 是否压缩LOGO
     * @return 二维码图片
     * @throws Exception
     */
    public static BufferedImage createImage(String content, String imgPath,
                                             boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        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);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }
 
    /**
     * 插入LOGO
     *
     * @param source       二维码图片
     * @param imgPath      LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception
     */
    public static void insertImage(BufferedImage source, String imgPath,
                                    boolean needCompress) throws Exception {
//        File file = new File(imgPath);
//        if (!file.exists()) {
//            System.err.println("" + imgPath + "   该文件不存在!");
//            return;
//        }
        Image src = ImageIO.read(new URL(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }
}


2。

 

public final class MatrixToImageWriter {
 
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
 
    private MatrixToImageWriter() {
    }
 
 
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
 
 
    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        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(BitMatrix matrix, String format, OutputStream stream)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}


 
 

3。

 
 
 

 

@Controller
public class QRcodeController {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(QRcodeController.class);
 
    //logo图片路径
    @Value("${logo.img.url}")
    private String IMG_PATH ;
 
 
    /**
     * 动态生成二维码流
     *
     * @param request
     * @param response
     * @param id       物品id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    public Object qrcode(HttpServletRequest request, HttpServletResponse response, String id) throws Exception {
        JSONObject object = new JSONObject();
        if (id == null) {
            id = "";
        }
        StringBuffer stringBuffer = new StringBuffer(id);
 
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
        ServletOutputStream sos = null;
        try {
            // 将图像输出到 Servlet输出流中。
            sos = response.getOutputStream();
            BufferedImage image = QRCodeUtil.createImage(val, IMG_PATH, true);
            ImageIO.write(image, "PNG", sos);
 
        } catch (Exception e) {
            LOGGER.error("生成二维码时发生异常", e);
        } finally {
            if (null != sos) {
                try {
                    sos.close();
                } catch (IOException e) {
                    LOGGER.error("生成二维码关闭输出流发生异常", e);
                }
            }
        }
        return null;
    }


 
   

 /**
     * 二维码导出
     * 字节流图片下载
     * @param id       床位或房间id
     * @param fileName 二维码的名称
     * @param type     bed生成床位二维码 room 生成房间二维码
     */
//    @RequestMapping(value = "/exportQRcode", method = RequestMethod.GET)
//    public void exportQRcode(HttpServletResponse response, String id, String fileName, String type) {
//        JSONObject object = new JSONObject();
//        if (StringUtils.isEmpty(id)) {
//            id = "";
//        }
//        if (Objects.equals("bed", type)) {
//            //查询床位的信息
//            DataMap dataMap = manageBedsService.selectBedByIdForQRcode(id);
//            if (!CollectionUtils.isEmpty(dataMap)){
//                object.put("areaName",dataMap.getString("areaName"));
//                object.put("buildingName",dataMap.getString("buildingName"));
//                object.put("roomName",dataMap.getString("roomName"));
//                object.put("bedName",dataMap.getString("bedName"));
//                object.put("id",dataMap.getString("id"));
//                fileName = dataMap.getString("areaName")+"-"
//                        +dataMap.getString("buildingName")+"-"
//                        +dataMap.getString("roomName")+"-"
//                        +dataMap.getString("bedName")+".png";
//            }
//        } else {
//            //查询房间的信息
//            DataMap dataMap = manageRoomService.selectRoomByIdForQRcode(id);
//            if (!CollectionUtils.isEmpty(dataMap)){
//                object.put("areaName",dataMap.getString("areaName"));
//                object.put("buildingName",dataMap.getString("buildingName"));
//                object.put("roomName",dataMap.getString("roomName"));
//                object.put("id",dataMap.getString("id"));
//                fileName = dataMap.getString("areaName")+"-"
//                        +dataMap.getString("buildingName")+"-"
//                        +dataMap.getString("roomName")+".png";
//            }
//        }
//        try {
//            int width = 300; // 图像宽度
//            int height = 300; // 图像高度
//            Map<EncodeHintType, Object> hints = new HashMap<>();
//            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(object.toJSONString(), BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
//            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
//            //bufferedImage转inputStream
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
//            ImageIO.write(bufferedImage, "png", imageOutput);
//            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//
//            response.reset(); // 非常重要
//            byte[] buf = new byte[1024];
//            int len = 0;
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/x-msdownload");
//            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
//            OutputStream out = response.getOutputStream();
//            while ((len = inputStream.read(buf)) > 0) {
//                out.write(buf, 0, len);
//            }
//            inputStream.close();
//            out.close();
//        } catch (WriterException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
 


   

 /**
     * 房间--床位的批量导出二维码
     *@param search 查询
     *@param level 树节点等级
     *@param nodeid 树id
     *@param type room /bed
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/batchGenerateQRcode", method = RequestMethod.GET)
//    public void batchGenerateQRcode(String search, String level, String nodeid, String type, HttpServletRequest request, HttpServletResponse response) {
//        InputStream inStream=null;
//        try {
//            List<DataMap> dataMapList=null;
//            String schoolCode = userSessionUtil.getCurrentUserSchoolCode(request);
//            if (Objects.equals("room",type)){
//                //获取房间列表
//                dataMapList = manageRoomService.batchGenerateRoomQRcode(search, level, nodeid, schoolCode);
//            }else if (Objects.equals("bed",type)){
//                //获取床位信息
//                dataMapList = manageBedsService.batchGenerateBedQRcode(search,level,nodeid,schoolCode);
//            }
//            if (!CollectionUtils.isEmpty(dataMapList)) {
//                //在根路径下创建一个文件夹
//                String rootPath = request.getSession().getServletContext().getRealPath(File.separator );
//                Date date = new Date();
//                long time = date.getTime();
//                File file = new File(rootPath +File.separator + time +File.separator );
//                boolean newFile = file.mkdir();
//                if (!newFile) {
//                    LOGGER.error("文件夹创建失败");
//                }
//                //循环写入二维码
//                for (DataMap room : dataMapList) {
//                    String pathName="";//图片的路径
//                    JSONObject jsonObject = new JSONObject();
//                    if (Objects.equals("room",type)) { //批量导出房间
//                        jsonObject.put("areaName", room.getString("areaName"));
//                        jsonObject.put("buildingName", room.getString("buildingName"));
//                        jsonObject.put("roomName", room.getString("roomName"));
//                        jsonObject.put("id", room.getString("id"));
//                        pathName = rootPath + File.separator  + time + File.separator
//                                +room.getString("areaName")+ "-"
//                                + room.getString("buildingName") + "-"
//                                + room.getString("roomName") + ".png";
//                    }else if(Objects.equals("bed",type)){
//                        jsonObject.put("areaName", room.getString("areaName"));
//                        jsonObject.put("buildingName", room.getString("buildingName"));
//                        jsonObject.put("roomName", room.getString("roomName"));
//                        jsonObject.put("bedName",room.getString("bedName"));
//                        jsonObject.put("id", room.getString("id"));
//                        pathName = rootPath + File.separator  + time + File.separator
//                                +room.getString("areaName")+ "-"
//                                + room.getString("buildingName") + "-"
//                                + room.getString("roomName")+"-"
//                                + room.getString("bedName")
//                                + ".png";
//                    }
//                    String text = jsonObject.toJSONString();
//                    //生成二维码图片,并返回图片路径
//                    QRcodeUtils.generateQRCode(text, pathName);
//                }
//                //压缩文件夹
//                String sourceFilePath = rootPath + File.separator  + time;
//                String zipFilePath = rootPath + File.separator ;
//                String fileName = time + "";
//                boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
//                if (!flag) {
//                    LOGGER.error("文件打包失败");
//                }
//                File fileZip = null;
//
//                //将文件夹弹出给页面response
//                fileZip = new File(rootPath + File.separator  + time + ".zip");
//                inStream = new FileInputStream(fileZip);
//                response.reset(); // 非常重要
//                byte[] buf = new byte[1024];
//                int len = 0;
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("application/x-msdownload");
//                response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
//                OutputStream out = response.getOutputStream();
//                while ((len = inStream.read(buf)) > 0)
//                    out.write(buf, 0, len);
//                inStream.close();
//                out.close();
//
//                //删除文件夹里所有二维码
//                File[] files = file.listFiles();
//                for (File fOrd : files) {
//                    fOrd.delete();
//                }
//                //删除文件夹
//                file.delete();
//                //删除压缩文件
//                fileZip.delete();
//            } else {
//                LOGGER.error("请选择要导出二维码的房间");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            try {
//                //关闭流
//                if(null !=inStream)inStream.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
//
//    }
 
}


4。

<!-- 二维码支持包 -->
        <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>


 
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值