利用google Zxing生成条形码/二维码的工具类

需要: 需要jar:core-3.3.3、core-3.3.3-sources、javase-3.3.3、javase-3.3.3-sources

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;
import java.util.Hashtable;

import javax.imageio.ImageIO;

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;
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.Result;
/**
 * 需要jar:core-3.3.3、core-3.3.3-sources、javase-3.3.3、javase-3.3.3-sources
 * @author 00
 *
 */
public class ZxingHandler {
	//private static Logger logger = LoggerFactory.getLogger(ZxingHandler.class);
	public static void encode(String contents, int width, int height, String imgPath)
	  {
	    int codeWidth = 95;
	    
	    codeWidth = Math.max(codeWidth, width);
	    try
	    {
	      BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);
	      
	      MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));
	    }
	    catch (Exception e)
	    {
	      //logger.error("条形码编码异常", e);
	    }
	  }
	  
	  public static String decode(String imgPath)
	  {
	    BufferedImage image = null;
	    Result result = null;
	    try
	    {
	      image = ImageIO.read(new File(imgPath));
	      if (image == null) {
	        System.out.println("the decode image may be not exit.");
	      }
	      LuminanceSource source = new BufferedImageLuminanceSource(image);
	      BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
	      
	      result = new MultiFormatReader().decode(bitmap, null);
	      return result.getText();
	    }
	    catch (Exception e)
	    {
	     // logger.error("条形码编码异常", e);
	    }
	    return null;
	  }
	  
	  public static void encode2(String contents, int width, int height, String imgPath)
	  {
	    Hashtable<EncodeHintType, Object> hints = new Hashtable();
	    
	    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
	    
	    hints.put(EncodeHintType.CHARACTER_SET, "GBK");
	    try
	    {
	      BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
	      
	      MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));
	    }
	    catch (Exception e)
	    {
	     // logger.error("二维码编码异常", e);
	    }
	  }
	  /**
	   * 生成base64二维码
	   * @param contents
	   * @param width
	   * @param height
	   * @return
	   */
	  public static String encode2Base64(String contents, int width, int height)
	  {
	    Hashtable<EncodeHintType, Object> hints = new Hashtable();
	    
	    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
	    
	    hints.put(EncodeHintType.CHARACTER_SET, "GBK");
	    try
	    {
	      BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
	      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	      MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
	      Base64.Encoder encoder = Base64.getEncoder();
	      String text = "data:image/png;base64," + encoder.encodeToString(outputStream.toByteArray());
	      //logger.debug("二维码编码Base64 内容{} 宽度{} 高度: {} BASE64: {}", new Object[] { contents, Integer.valueOf(width), Integer.valueOf(height), text });
	      return text;
	    }
	    catch (Exception e)
	    {
	     // logger.error("二维码编码Base64异常", e);
	    }
	    return null;
	  }
	  /**
	   * 二维码解码
	   * @param imgPath
	   * @return
	   */
	  public static String decode2(String imgPath)
	  {
	    BufferedImage image = null;
	    Result result = null;
	    try
	    {
	      image = ImageIO.read(new File(imgPath));
	      if (image == null) {
	        System.out.println("the decode image may be not exit.");
	      }
	      LuminanceSource source = new BufferedImageLuminanceSource(image);
	      BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
	      
	      Hashtable<DecodeHintType, Object> hints = new Hashtable();
	      hints.put(DecodeHintType.CHARACTER_SET, "GBK");
	      
	      result = new MultiFormatReader().decode(bitmap, hints);
	      return result.getText();
	    }
	    catch (Exception e)
	    {
	   //   logger.error("二维码解码文件异常", e);
	    }
	    return null;
	  }
	  
	  public static void main(String[] args)
	  {
	    String imgPath = "target\\zxing_EAN13.png";
	    String contents = "6923450657713";
	    int width = 105;int height = 50;
	    
	    encode(contents, width, height, imgPath);
	    System.out.println("finished zxing EAN-13 encode.");
	    
	    String decodeContent = decode(imgPath);
	    System.out.println("解码内容如下" + decodeContent);
	    System.out.println("finished zxing EAN-13 decode.");
	    
	    String imgPath2 = "target\\zxing.png";
	    String contents2 = "Hello , welcome to Using Zxing!\nWebSite [ https://www.baidu.com ]\nEMail [ XXX@gzviewit.com ]";
	    
	    int width2 = 300;int height2 = 300;
	    
	    encode2(contents2, width2, height2, imgPath2);
	    System.out.println("finished zxing encode.");
	    
	    String decodeContent2 = decode2(imgPath2);
	    System.out.println("解码内容如下:" + decodeContent2);
	    System.out.println("finished zxing decode.");
	    
	    String base64str = encode2Base64("https://github.com/alibaba/fastjson", 600, 600);
	    System.out.println("解码内容如下" + base64str);
	  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值