package com . ccthanking . framework . util ;
import java.awt.image.BufferedImage ;import java.io.ByteArrayOutputStream ;import java.io.File ;import java.io.IOException ;import java.util.Hashtable ;
import javax.imageio.ImageIO ;
import sun.misc.BASE64Encoder ;
import com.google.zxing.BarcodeFormat ;import com.google.zxing.EncodeHintType ;import com.google.zxing.MultiFormatWriter ;import com.google.zxing.WriterException ;import com.google.zxing.client.j2se.MatrixToImageWriter ;import com.google.zxing.common.BitMatrix ;
/*** @author CaoWeiJie* 二维码生成*/public class ZxingUtil {//创建二维码public static String createQrCode ( String par ){
//大小int width = 300 ;int height = 300 ;//格式String format = "png" ;String res = "" ;try {
Hashtable hints = new Hashtable ();hints . put ( EncodeHintType . CHARACTER_SET , "utf-8" );BitMatrix bitMatrix = new MultiFormatWriter (). encode ( par , BarcodeFormat . QR_CODE , width , height , hints );bitMatrix = deleteWhite ( bitMatrix );BufferedImage image = MatrixToImageWriter . toBufferedImage ( bitMatrix );ByteArrayOutputStream os = new ByteArrayOutputStream (); //新建流。ImageIO . write ( image , format , os ); //利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。byte b [] = os . toByteArray (); //从流中获取数据数组。res = new BASE64Encoder (). encode ( b );} catch ( WriterException e ) {// TODO Auto-generated catch blockSystem . out . println ( "QrCode bitMatrix操作出错" );e . printStackTrace ();} catch ( IOException e ) {// TODO Auto-generated catch blockSystem . out . println ( "writeToFile操作出错" );e . printStackTrace ();}return res ;}/*** 删除二维码白边框* @param matrix* @return*/public static BitMatrix deleteWhite ( BitMatrix matrix ){int [] rec = matrix . getEnclosingRectangle ();int resWidth = rec [ 2 ] + 1 ;int resHeight = rec [ 3 ] + 1 ;BitMatrix resMatrix = new BitMatrix ( resWidth , resHeight );resMatrix . clear ();for ( int i = 0 ; i < resWidth ; i ++) {for ( int j = 0 ; j < resHeight ; j ++) {if ( matrix . get ( i + rec [ 0 ], j + rec [ 1 ]))resMatrix . set ( i , j );}}return resMatrix ;}}
Java 生成二维码
最新推荐文章于 2024-06-18 11:48:02 发布