欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java ZXing生成二维码及条码实例分享

程序员文章站 2024-03-09 10:13:23
1、jar包:   zxing-core-3.3.0.jar           zxing-javase-3.3.0.jar ...

1、jar包:   zxing-core-3.3.0.jar   

       zxing-javase-3.3.0.jar  

bufferedimageluminancesource.java

package com.webos.util;
import java.awt.graphics2d;
import java.awt.geom.affinetransform;
import java.awt.image.bufferedimage;
import com.google.zxing.luminancesource;
public class bufferedimageluminancesource extends luminancesource {
 private final bufferedimage image;
 private final int left;
 private final int top;
 public bufferedimageluminancesource(bufferedimage image) {
  this(image, 0, 0, image.getwidth(), image.getheight());
 }
 public bufferedimageluminancesource(bufferedimage image, int left, int top, int width, int height) {
  super(width, height);
  int sourcewidth = image.getwidth();
  int sourceheight = image.getheight();
  if (left + width > sourcewidth || top + height > sourceheight) {
   throw new illegalargumentexception("crop rectangle does not fit within image data.");
  }
  for (int y = top; y < top + height; y++) {
   for (int x = left; x < left + width; x++) {
    if ((image.getrgb(x, y) & 0xff000000) == 0) {
     image.setrgb(x, y, 0xffffffff); // = white
    }
   }
  }
  this.image = new bufferedimage(sourcewidth, sourceheight, bufferedimage.type_byte_gray);
  this.image.getgraphics().drawimage(image, 0, 0, null);
  this.left = left;
  this.top = top;
 }
 public byte[] getrow(int y, byte[] row) {
  if (y < 0 || y >= getheight()) {
   throw new illegalargumentexception("requested row is outside the image: " + y);
  }
  int width = getwidth();
  if (row == null || row.length < width) {
   row = new byte[width];
  }
  image.getraster().getdataelements(left, top + y, width, 1, row);
  return row;
 }
 public byte[] getmatrix() {
  int width = getwidth();
  int height = getheight();
  int area = width * height;
  byte[] matrix = new byte[area];
  image.getraster().getdataelements(left, top, width, height, matrix);
  return matrix;
 }
 public boolean iscropsupported() {
  return true;
 }
 public luminancesource crop(int left, int top, int width, int height) {
  return new bufferedimageluminancesource(image, this.left + left, this.top + top, width, height);
 }
 public boolean isrotatesupported() {
  return true;
 }
 public luminancesource rotatecounterclockwise() {
  int sourcewidth = image.getwidth();
  int sourceheight = image.getheight();
  affinetransform transform = new affinetransform(0.0, -1.0, 1.0, 0.0, 0.0, sourcewidth);
  bufferedimage rotatedimage = new bufferedimage(sourceheight, sourcewidth, bufferedimage.type_byte_gray);
  graphics2d g = rotatedimage.creategraphics();
  g.drawimage(image, transform, null);
  g.dispose();
  int width = getwidth();
  return new bufferedimageluminancesource(rotatedimage, top, sourcewidth - (left + width), getheight(), width);
 }
}

qrcodeutil.java

package com.webos.util;
import java.awt.basicstroke;
import java.awt.graphics;
import java.awt.graphics2d;
import java.awt.image;
import java.awt.shape;
import java.awt.geom.roundrectangle2d;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.outputstream;
import java.util.hashtable;
import java.util.random;
import javax.imageio.imageio;
import com.google.zxing.barcodeformat;
import com.google.zxing.binarybitmap;
import com.google.zxing.decodehinttype;
import com.google.zxing.encodehinttype;
import com.google.zxing.multiformatreader;
import com.google.zxing.multiformatwriter;
import com.google.zxing.common.bitmatrix;
import com.google.zxing.common.hybridbinarizer;
import com.google.zxing.qrcode.decoder.errorcorrectionlevel;
/**
* @classname: qrcodeutil 
* @description: 二维码编码
* @author liuy
* @date 2016年7月9日 下午3:03:24 
* 
*/
public class qrcodeutil {
 // 设置二维码编码格式
 private static final string charset = "utf-8";
 // 保存的二维码格式
 private static final string format_name = "jpg";
 // 二维码尺寸
 private static final int qrcode_size = 800;
 // logo宽度
 private static final int logo_width = 80;
 // logo高度
 private static final int logo_height = 80;
 /**
  * @title: createimage
  * @description: 将二维码内容创建到image流
  * @param content 二维码内容
  * @param imgpath logo图片地址
  * @param needcompress 是否压缩logo图片大小
  * @return
  * @throws exception 参数说明
  * @return bufferedimage 返回类型
  * @throws
  */
 private static bufferedimage createimage(string content, string logopath, boolean needcompress) throws exception {
  hashtable<encodehinttype, object> hints = new hashtable<encodehinttype, object>();
  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 (logopath == null || "".equals(logopath)) {
   return image;
  }
  // 插入logo
  qrcodeutil.insertimage(image, logopath, needcompress);
  return image;
 }
 /**
  * @title: insertimage
  * @description: 将logo插入到二维码中
  * @param source 二维码image流
  * @param imgpath logo地址
  * @param needcompress 是否压缩大小
  * @throws exception 参数说明
  * @return void 返回类型
  * @throws
  */
 private static void insertimage(bufferedimage source, string logopath, boolean needcompress) throws exception {
  file file = new file(logopath);
  if (!file.exists()) {
   system.err.println("" + logopath + " 该文件不存在!");
   return;
  }
  image src = imageio.read(new file(logopath));
  int width = src.getwidth(null);
  int height = src.getheight(null);
  if (needcompress) { // 压缩logo
   if (width > logo_width) {
    width = logo_width;
   }
   if (height > logo_height) {
    height = logo_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();
 }
 /**
  * @title: mkdirs
  * @description: 创建文件夹
  * @param destpath 文件夹地址
  * @return void 返回类型
  * @throws
  */
 private static boolean mkdirs(string destpath) {
  file file = new file(destpath);
  // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
  if (!file.exists() && !file.isdirectory()) {
   file.mkdirs();
   return true;
  }
  return false;
 }
 /**
  * @title: encode
  * @description: 生成二维码
  * @param content 二维码内容
  * @param imgpath logo图片地址
  * @param destpath 目标保存地址
  * @param needcompress 是否压缩logo图片大小
  * @throws exception 参数说明
  * @return void 返回类型
  * @throws
  */
 private static void encode(string content, string logopath, string destpath, boolean needcompress) throws exception {
  bufferedimage image = qrcodeutil.createimage(content, logopath, needcompress);
  if (mkdirs(destpath)) {
   string file = new random().nextint(99999999) + ".jpg";
   imageio.write(image, format_name, new file(destpath + "/" + file));
  }
 }
 /**
  * @title: encode
  * @description: 生成二维码
  * @param content 二维码内容
  * @param destpath 目标保存地址
  * @throws exception 参数说明
  * @return void 返回类型
  * @throws
  */
 public static void encode(string content, string destpath) throws exception {
  qrcodeutil.encode(content, null, destpath, false);
 }
 /**
  * @title: encode
  * @description: 生成二维码
  * @param content 二维码内容
  * @param imgpath logo图片地址
  * @param output 输出流
  * @param needcompress 是否压缩logo图片大小
  * @throws exception 参数说明
  * @return void 返回类型
  * @throws
  */
 public static void encode(string content, string logopath, outputstream output, boolean needcompress) throws exception {
  bufferedimage image = qrcodeutil.createimage(content, logopath, needcompress);
  imageio.write(image, format_name, output);
 }
 /**
  * @title: encode
  * @description: 生成二维码
  * @param content 二维码内容
  * @param output 输出流
  * @throws exception 参数说明
  * @return void 返回类型
  * @throws
  */
 public static void encode(string content, outputstream output) throws exception {
  qrcodeutil.encode(content, null, output, false);
 }
 /**
  * @title: decode
  * @description: 对二维码解码
  * @param file 文件对象
  * @return 解码后的二维码内容字符串
  * @throws exception 参数说明
  * @return string 返回类型
  * @throws
  */
 private 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));
  hashtable<decodehinttype, string> hints = new hashtable<decodehinttype, string>();
  hints.put(decodehinttype.character_set, charset);
  return new multiformatreader().decode(bitmap, hints).gettext();
 }
 /**
  * @title: decode
  * @description: 对二维码解码
  * @param path 文件路径
  * @return
  * @throws exception 参数说明
  * @return string 返回类型
  * @throws
  */
 public static string decode(string path) throws exception {
  return qrcodeutil.decode(new file(path));
 }
}

qrcodeservlet.java

package com.webos.servlet;
import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import com.webos.util.qrcodeutil;
/*
 * servlet implementation class qrcodeservlet
 */
@webservlet("/qrcodeservlet")
public class qrcodeservlet extends httpservlet {
 private static final long serialversionuid = 1l;
 /*
  * @see httpservlet#httpservlet()
  */
 public qrcodeservlet() {
  super();
 }
 /*
  * @see httpservlet#doget(httpservletrequest request, httpservletresponse
  * response)
  */
 protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  try {
   string text = "http://www.baidu.com?timestamp=" + system.currenttimemillis();
   qrcodeutil.encode(text, response.getoutputstream());
  } catch (exception e) {
   e.printstacktrace();
  }
 }
 /*
  * @see httpservlet#dopost(httpservletrequest request, httpservletresponse
  * response)
  */
 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  // todo auto-generated method stub
  doget(request, response);
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!