java生成二维码

//生成二维码
    @RequestMapping("/getQRCode")
    @ResponseBody
    public HashMap<String, Object> getQRCode(HttpServletRequest request, HttpServletResponse response,String id) throws Exception{
        int serverPort = request.getServerPort();
        String serverName = "http://"+ myHost + ":" + serverPort + contextPath;
        if(StringUtils.isBlank(id)) {
            return R.error("主键值不能为空,请修改。");
        }
        String tablename = "AM_Signin";
        HashMap<String, Object> obj = service.getMapByKey(tablename, id);
        String name = (String)obj.get("name");
        MySqlData mySqlData = new MySqlData();
        //数据库表名
        mySqlData.setTableName("AM_Signin");
        //保存默认值
//        mySqlData.setFieldValue("qrstatus", "1");//二维码状态,1:已生成
        mySqlData.setFieldWhere("id", id, "=");

        //二维码生成对象QRCodeWriter
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        String url = serverName + "/Achievements/AM_Signinuser/Add?activityid="+id;//扫二维码访问的地址
        int widthHeight = 500;
        BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE,widthHeight,widthHeight);
        String realPath = request.getSession().getServletContext().getRealPath("/QRCode/");
//        realPath = realPath.replaceAll("\\\\","/");
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = newDate.getDate("yyyyMMdd")+(new Random().nextInt(900000)+100000)+name+".png";
        mySqlData.setFieldValue("qrname", fileName);
        service.update(request, mySqlData);//修改二维码的生成状态
        String filePath = realPath + fileName;
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path);//将二维码图片写进文件夹
        //导出图片
        File readFile = new File(filePath);
        FileInputStream is = new FileInputStream(readFile);
        // 3. 获取响应输出流
        response.setContentType("text/plain;charset=UTF-8");
        // 4. 附件下载 attachment 附件 inline 在线打开(默认值)
        //处理下载后的文件,文件名不显示或乱码问题
        String filename = new String(fileName.getBytes(), "ISO-8859-1");
        response.setHeader("content-disposition", "attachment;fileName=" + filename);
        // 5. 处理下载流复制
        ServletOutputStream os = response.getOutputStream();
        int len;
        byte[] b = new byte[1024];
        while(true){
            len = is.read(b);
            if(len == -1) break;
            os.write(b, 0, len);
        }
        // 释放资源
        os.close();
        is.close();
        return R.ok();
    }
	
		com.google.zxing
		core
		3.3.0
	
	
		com.google.zxing
		javase
		3.3.0
	

你可能感兴趣的:(JAVA,java,servlet,开发语言)