二维码java生成代码

二维码java生成代码

前几天在做一个app小项目时要封装一个二维码生类,于是今天有空想把代码记录下来,所以今天要写的是二维码生成工具类,2012年的时候满大街都是二维码推广,当时还在学编程的我就很好奇是个什么东西,后来去了解了下原来就是一个链接,再后来就没有接触过二维码这一块,目前很多网站可以直接url转化生成二维码,其实道理都很简单,按规则写个图片嘛,废话不多说,进入正题。

将此次需要借助的是com.google.zxing-3.1.0.jar包,大家可以去maven仓库下载,若使用maven管理项目的则添加相应依赖,中央仓库有提示,接下来我们进入代码环节,需要注意的是3.1.0提供的这个版本需要jdk7以上的版本,所以若使用这个版本的包更换到jdk7才能运行(2.x的版本可以使用jdk1.6)


以下是java代码:

public class BuildQRCode extends HttpServlet{private static final long serialVersionUID = -5799782462647593816L;@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse response)throws ServletException, IOException {String imageContent="http://www.baidu.com";int width = 300; // 图像宽度int height = 300; // 图像高度try {//项目资源的网络路径 这里我就不获取拼接了,直接写死String imgPath ="http://127.0.0.1:8080/studyProject/image/a.png";//logo图片的路径 BufferedImage image = QRCodeImgUtils.buildQR(imageContent, width, height, true, imgPath);// 禁止浏览缓存随机图片response.setDateHeader("Expires", -1);response.setHeader("Cache-Control", "no-cache");response.setHeader("Pragma", "no-cache");// 通知客户机以图片方式打开发送过去的数据response.setHeader("Content-Type", "image/jpeg"); // 以response流的形式输出图片ImageIO.write(image, "jpg", response.getOutputStream());}catch (IOException e) {e.printStackTrace();}}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}
}

util处理内封装如下:

class QRCodeImgUtils{private static final int BLACK = 0xFF000000;private static final int WHITE = 0xFFFFFFFF;/*** 参数准备* @param imageContent 内容* @param width 宽度* @param height 高度* @param logoFlag 是否插入中心图标* @param imgPath 中心图标路径* @return*/public static BufferedImage buildQR(String imageContent,int width,int height,boolean logoFlag,String imgPath){Map hints = new HashMap();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");hints.put(EncodeHintType.MARGIN, 1); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);BitMatrix bitMatrix=null;try {bitMatrix = new MultiFormatWriter().encode(imageContent, BarcodeFormat.QR_CODE, width, height, hints);} catch (WriterException e) {e.printStackTrace();}BufferedImage image = toBufferedImage(bitMatrix,logoFlag,imgPath);return image;}/*** 生成矩阵* @param matrix* @param insertFlag 是否插入中心图标* @param imgPath 图标路径* @return*/public static BufferedImage toBufferedImage(BitMatrix matrix,boolean insertFlag,String imgPath) {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);}}if(insertFlag){// 插入图片  boolean needCompress = true;//需要压缩try {insertImage(image, imgPath, needCompress);} catch (Exception e) {e.printStackTrace();}}return image;}/** * 插入LOGO *  * @param source *            二维码图片 * @param imgPath *            LOGO图片地址 * @param needCompress *            是否压缩 * @throws Exception */  public static void insertImage(BufferedImage source, String imgPath,  boolean needCompress){  //new一个URL对象  URL url=null;Image src=null ;try {url = new URL(imgPath);src= ImageIO.read(url);  } catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}  int width = src.getWidth(null);  int height = src.getHeight(null);  if (needCompress) { // 压缩LOGO  if (width > 60) {  width = 60;  }  if (height > 60) {  height = 60;  }  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 = (300 - width) / 2;  int y = (300 - 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();  } 
}

目录结构如下:



访问返回如下:






本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部