二维码生成及扫描,查看附件

前面先附上代码,具体的类方法放在最后
            //二维码生成地址
            String path = "C:/qrCode/"+sdf.format(new Date())+"/"+id+".jpg";
            // 生成二维码
            String content = "http://221.6.30.xxx:xxxx/xxxx/xx/xxxx.do?rowId="+id;
            QrCodeCreateUtil.encode(content, path);

  展示二维码前台jsp:

<table class="table table-condensed table-hover">
    <tbody>
    <tr>
        <td align="center">
            <img src="<%=basePath%>xx/QR-code-show.do?rowId=${xxxxxxx.rowId}">
        </td>
    </tr>
    </tbody>
</table>

  后台二维码显示并下载

@RequestMapping(method = RequestMethod.GET, value = "QR-code-show")
public void xxxxx(String rowId, HttpServletRequest request, HttpServletResponse response) throws IOException {
   if(rowId != null && rowId.length() > 0){
      //我是通过rowId获取的二维码路径
      String qrCode = equipmentInfo.getQrCode();
      //附件
      String fileName = equipmentInfo.getManagerNum()+".jpg";
      FileUtil fileHelper = new FileUtil();
      //下载
      fileHelper.downloadFile(qrCode, request, response, fileName);
   }
}
/**
 * 下载文件
 * 
 * @param downLoadPath
 *            下载路径
 * @param response
 * @param fileName
 *            文件名
 */
public void downloadFile(String downLoadPath, HttpServletRequest request,
      HttpServletResponse response, String fileName) {
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   try {
      long fileLength = new File(downLoadPath).length();
      /*
       * response.setContentType("application/x-msdownload;");
       * response.setHeader("Content-disposition", "attachment; filename="
       * + fileName);
       */

      String userAgent = request.getHeader("User-Agent");
      // 针对IE或者以IE为内核的浏览器:
      if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
         fileName = URLEncoder.encode(fileName, "UTF-8");
      } else {
         // 非IE浏览器的处理:
         fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
      }
      response.setHeader("Content-disposition",
            String.format("attachment; filename=\"%s\"", fileName));
      response.setContentType("application/octet-stream;charset=utf-8");
      response.setCharacterEncoding("UTF-8");

      response.setHeader("Content-Length", String.valueOf(fileLength));
      bis = new BufferedInputStream(new FileInputStream(downLoadPath));
      bos = new BufferedOutputStream(response.getOutputStream());
      byte[] buff = new byte[2048];
      int bytesRead;
      while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
         bos.write(buff, 0, bytesRead);
      }
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
      if (bis != null) {
         try {
            bis.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      if (bos != null) {
         try {
            bos.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
   }

}

根据生成二维码 存放的content 扫描发送请求  "http://221.6.30.xxx:xxxx/xxxx/xx/xxxx.do?rowId="+id;

/**
 * 查看设备信息(二维码扫描)
 * @param rowId
 * @param model
 * @return
 */
@RequestMapping("get-sb-info")
public String getSbInfo(@RequestParam(value = "rowId") String rowId, Model model) {
   String returnPage = "xx/xxxx";
   if (rowId != null) {
      EquipmentInfo equipmentInfo = equipmentInfoManager.get(rowId);
      model.addAttribute("equipmentInfo", equipmentInfo);
      List<FileRecord> fileList = fileRecordManager.findBy("relationId", rowId);
      model.addAttribute("fileList", fileList);
   }else{
      returnPage = "";
   }
   return returnPage;
}

跳转jsp后显示内容

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/common/taglibs.jsp"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath %>">
<html>
<body style="text-align: center;margin: 0px;padding: 0px;">
<div style="margin:0 auto;width: 100%;">
    <table  class="bordertable" cellpadding="0" cellspacing="0">
     
        <tr>
            <td align="right" class="titlebg">xxxx:</td>
            <td align="left">${equipmentInfo.workStatus}</td>
        </tr>
        <c:forEach items="${fileList}" var="file">
            <tr>
                <td colspan="2" width="100%"><img src="<%=basePath%>fileRecord/fileDownload.do?fileId=${file.rowId}" width="100%"></td>
            </tr>
        </c:forEach>
    </table>
</div>
</body>
</html>

最后显示下载文件

/**
 * 附件下载
 * 
 * @param fileId
 *            文件ID
 * @return 下载
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.GET, value = "fileDownload")
public void fileDownLoad(String fileId, HttpServletRequest request,
      HttpServletResponse response) throws IOException {
   FileRecord fileRecord = fileRecordManager.get(fileId);
   String filePath = fileRecord.getFilePath();
   String fileName = fileRecord.getFileName();
   FileUtil fileHelper = new FileUtil();
   fileHelper.downloadFile(filePath, request, response, fileName);
}

最后贴上二维码类  zxing-code-2.3.jar

package com.gx.soft.common.util;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import java.util.Hashtable;

public class QrCodeCreateUtil {

   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 = 60;
   // LOGO高度
   private static final int HEIGHT = 60;

// /**
//  * 生成包含字符串信息的二维码图片
//  * @param outputStream 输出流
//  * @param content 字符串信息
//  * @param qrCodeSize 二维码图片大小
//  * @param imageFormat 二维码的格式
//  * @return
//  * @throws WriterException
//  * @throws IOException
//  */
// public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{
//    //设置二维码纠错级别Map
//    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
//    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别
//    QRCodeWriter qrCodeWriter = new QRCodeWriter();
//    //创建比特矩阵(位矩阵)的QR码编码的字符串
//    BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
//    // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
//    int matrixWidth = byteMatrix.getWidth();
//    BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
//    image.createGraphics();
//    Graphics2D graphics = (Graphics2D) image.getGraphics();
//    graphics.setColor(Color.WHITE);
//    graphics.fillRect(0, 0, matrixWidth, matrixWidth);
//    // 使用比特矩阵画并保存图像
//    graphics.setColor(Color.BLACK);
//    for (int i = 0; i < matrixWidth; i++){
//       for (int j = 0; j < matrixWidth; j++){
//          if (byteMatrix.get(i, j)){
//             graphics.fillRect(i-100, j-100, 1, 1);
//          }
//       }
//    }
//    return ImageIO.write(image, imageFormat, outputStream);
// }



   private 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;
      }
      // 插入图片
      QrCodeCreateUtil.insertImage(image, imgPath, needCompress);
      return image;
   }

   private 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 File(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();
   }

   public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
      BufferedImage image = QrCodeCreateUtil.createImage(content, imgPath, needCompress);
      mkdirs(destPath);
      // String file = new Random().nextInt(99999999)+".jpg";
      // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
      ImageIO.write(image, FORMAT_NAME, new File(destPath));
   }

   public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
      BufferedImage image = QrCodeCreateUtil.createImage(content, imgPath, needCompress);
      return image;
   }

   public static void mkdirs(String destPath) {
      File file = new File(destPath);
      // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
      if (!file.exists() && !file.isDirectory()) {
         file.mkdirs();
      }
   }

   public static void encode(String content, String imgPath, String destPath) throws Exception {
      QrCodeCreateUtil.encode(content, imgPath, destPath, false);
   }

   public static void encode(String content, String destPath) throws Exception {
      QrCodeCreateUtil.encode(content, null, destPath, false);
   }

   public static void encode(String content, String imgPath, OutputStream output, boolean needCompress) throws Exception {
      BufferedImage image = QrCodeCreateUtil.createImage(content, imgPath, needCompress);
      ImageIO.write(image, FORMAT_NAME, output);
   }

   public static void encode(String content, OutputStream output) throws Exception {
      QrCodeCreateUtil.encode(content, null, output, false);
   }

   public static String decode(File file) throws Exception {
      BufferedImage image;
      image = ImageIO.read(file);
      if (image == null) {
         return null;
      }
      BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
      BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
      Result result;
      Hashtable hints = new Hashtable();
      hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
      result = new MultiFormatReader().decode(bitmap, hints);
      String resultStr = result.getText();
      return resultStr;
   }

   public static String decode(String path) throws Exception {
      return QrCodeCreateUtil.decode(new File(path));
   }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值