Zxing二维码

来源:互联网 发布:java前台上传文件 编辑:程序博客网 时间:2024/04/30 20:06

最近项目中有生成二维码的需求,就各种Google,整出了基本的demo。

用的是Zxing,网上有两种代码,主要区别于MatrixToImageWriter.writeToFile的方法中传入的是BitMatrix或者ByteMatrix.

demo中支持二维码中间带小logo图片,其中的边框也是另一张图片;嵌入的主要原理就是在Zxing生成的二维码上绘边框图,再绘Logo图,需要计算一下坐标;

对二维码内容使用了org.apache.commons.codec.binary.Base64加密解密,了解了一下Base64的原理,参考http://aub.iteye.com/blog/1129273;

package qrcode;import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Hashtable;import java.util.Map;import javax.imageio.ImageIO;import org.apache.commons.codec.binary.Base64;import com.google.zxing.BarcodeFormat;import com.google.zxing.BinaryBitmap;import com.google.zxing.DecodeHintType;import com.google.zxing.EncodeHintType;import com.google.zxing.LuminanceSource;import com.google.zxing.MultiFormatReader;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.Result;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/** * Zxing生成二维码,解析二维码 * Base64对内容进行加密解密 */public class ZxingUtil {private static final String CHARACTER_SET = "UTF-8";private static final String IMAGE_TYPE = "png";private static final String BORDER_IMAGE_PATH = "D:\\tttt\\qr_bg.png";/** * 生成二维码 * @Author: XuYanbo * @Date: 2014-5-7 * @param content * @param width * @param height * @param imgPath */public void encode(String content, int width, int height, String imgPath, String logoPath){Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();//指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//指定编码hints.put(EncodeHintType.CHARACTER_SET, CHARACTER_SET);try {//将元数据内容加密BitMatrix matrix = new MultiFormatWriter().encode(new String(Base64.encodeBase64(content.getBytes())), BarcodeFormat.QR_CODE, width, height, hints);//MatrixToImageWriter.writeToFile(matrix, IMAGE_TYPE, new File(imgPath));//填充Logoif(logoPath!=null && !"".equals(logoPath)){//读取二维码本身内容BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);        for(int x=0;x<width;x++){            for(int y=0;y<height;y++){            img.setRGB(x, y, matrix.get(x, y) == true ? Color.BLACK.getRGB() : Color.WHITE.getRGB());              }          }  /*返回由指定矩形区域定义的子图像*/            BufferedImage bi2 = img.getSubimage(width*5/12, height*5/12-3, width/6+2, height/6+2);                        /*获取一个绘图工具笔*/            Graphics2D g2 = bi2.createGraphics();                        /*读取Logo图片信息*/  BufferedImage logo = ImageIO.read(new File(logoPath));BufferedImage border = ImageIO.read(new File(BORDER_IMAGE_PATH));                        /*绘制图片*/            g2.drawImage(border, 0, 0, width/6+2, height/6+2, null);            g2.drawImage(logo, 0, 0, width/6, height/6, null);            g2.dispose();            img.flush();            ImageIO.write(img, IMAGE_TYPE, new File(imgPath));} else {MatrixToImageWriter.writeToFile(matrix, IMAGE_TYPE, new File(imgPath));}} catch (WriterException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/** * 解析二维码 * @Author: XuYanbo * @Date: 2014-5-7 * @param imgPath * @return String */public String decode(String imgPath){String res = null;try {BufferedImage image = ImageIO.read(new File(imgPath));Result result = null;if(image==null){System.out.println("image not exist.");} else {LuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Hashtable<Object, Object> hints = new Hashtable<Object, Object>();hints.put(DecodeHintType.CHARACTER_SET, CHARACTER_SET);result = new MultiFormatReader().decode(bitmap);res = result.getText();}} catch (IOException e) {e.printStackTrace();} catch (NotFoundException e) {e.printStackTrace();}return res;}public static void main(String[] args) {String timeTag = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());String imgPath = "D:\\tttt\\qrcode" + timeTag + "." + IMAGE_TYPE;String logoPath = "D:\\tttt\\gmlogo.png";String content = "vincent,xuyanbo,Java Developer,测试一下能放多少字符;\r\n" +"1234567890一二三四五六七八九十\r\n1234567890一二三四五六七八九十";System.out.println(content.length()+" characters..");//650 maxint width = 300, height = 300;ZxingUtil zxingUtil = new ZxingUtil();zxingUtil.encode(content, width, height, imgPath, logoPath);System.out.println("Generate Over..[" + imgPath + "]");String res = zxingUtil.decode(imgPath);System.out.println("Decode Result: ["+res+"]");System.out.println("Decode Content: ["+new String(Base64.decodeBase64(res.getBytes()))+"]");}}




0 0
原创粉丝点击