java ZXing生成二维码及条码实例分享
1、jar包: ZXing-core-3.3.0.jarhttp://mvnrepository.com/artifact/com.google.zxing/core
ZXing-javase-3.3.0.jar http://mvnrepository.com/artifact/com.google.zxing/javase
BufferedImageLuminanceSource.java
packagecom.webos.util;
importjava.awt.Graphics2D;
importjava.awt.geom.AffineTransform;
importjava.awt.image.BufferedImage;
importcom.google.zxing.LuminanceSource;
publicclassBufferedImageLuminanceSourceextendsLuminanceSource{
privatefinalBufferedImageimage;
privatefinalintleft;
privatefinalinttop;
publicBufferedImageLuminanceSource(BufferedImageimage){
this(image,0,0,image.getWidth(),image.getHeight());
}
publicBufferedImageLuminanceSource(BufferedImageimage,intleft,inttop,intwidth,intheight){
super(width,height);
intsourceWidth=image.getWidth();
intsourceHeight=image.getHeight();
if(left+width>sourceWidth||top+height>sourceHeight){
thrownewIllegalArgumentException("Croprectangledoesnotfitwithinimagedata.");
}
for(inty=top;y<top+height;y++){
for(intx=left;x<left+width;x++){
if((image.getRGB(x,y)&0xFF000000)==0){
image.setRGB(x,y,0xFFFFFFFF);//=white
}
}
}
this.image=newBufferedImage(sourceWidth,sourceHeight,BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image,0,0,null);
this.left=left;
this.top=top;
}
publicbyte[]getRow(inty,byte[]row){
if(y<0||y>=getHeight()){
thrownewIllegalArgumentException("Requestedrowisoutsidetheimage:"+y);
}
intwidth=getWidth();
if(row==null||row.length<width){
row=newbyte[width];
}
image.getRaster().getDataElements(left,top+y,width,1,row);
returnrow;
}
publicbyte[]getMatrix(){
intwidth=getWidth();
intheight=getHeight();
intarea=width*height;
byte[]matrix=newbyte[area];
image.getRaster().getDataElements(left,top,width,height,matrix);
returnmatrix;
}
publicbooleanisCropSupported(){
returntrue;
}
publicLuminanceSourcecrop(intleft,inttop,intwidth,intheight){
returnnewBufferedImageLuminanceSource(image,this.left+left,this.top+top,width,height);
}
publicbooleanisRotateSupported(){
returntrue;
}
publicLuminanceSourcerotateCounterClockwise(){
intsourceWidth=image.getWidth();
intsourceHeight=image.getHeight();
AffineTransformtransform=newAffineTransform(0.0,-1.0,1.0,0.0,0.0,sourceWidth);
BufferedImagerotatedImage=newBufferedImage(sourceHeight,sourceWidth,BufferedImage.TYPE_BYTE_GRAY);
Graphics2Dg=rotatedImage.createGraphics();
g.drawImage(image,transform,null);
g.dispose();
intwidth=getWidth();
returnnewBufferedImageLuminanceSource(rotatedImage,top,sourceWidth-(left+width),getHeight(),width);
}
}
QRCodeUtil.java
packagecom.webos.util;
importjava.awt.BasicStroke;
importjava.awt.Graphics;
importjava.awt.Graphics2D;
importjava.awt.Image;
importjava.awt.Shape;
importjava.awt.geom.RoundRectangle2D;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.OutputStream;
importjava.util.Hashtable;
importjava.util.Random;
importjavax.imageio.ImageIO;
importcom.google.zxing.BarcodeFormat;
importcom.google.zxing.BinaryBitmap;
importcom.google.zxing.DecodeHintType;
importcom.google.zxing.EncodeHintType;
importcom.google.zxing.MultiFormatReader;
importcom.google.zxing.MultiFormatWriter;
importcom.google.zxing.common.BitMatrix;
importcom.google.zxing.common.HybridBinarizer;
importcom.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
*@ClassName:QRCodeUtil
*@Description:二维码编码
*@authorLiuy
*@date2016年7月9日下午3:03:24
*
*/
publicclassQRCodeUtil{
//设置二维码编码格式
privatestaticfinalStringCHARSET="utf-8";
//保存的二维码格式
privatestaticfinalStringFORMAT_NAME="JPG";
//二维码尺寸
privatestaticfinalintQRCODE_SIZE=800;
//LOGO宽度
privatestaticfinalintLOGO_WIDTH=80;
//LOGO高度
privatestaticfinalintLOGO_HEIGHT=80;
/**
*@Title:createImage
*@Description:将二维码内容创建到Image流
*@paramcontent二维码内容
*@paramimgPathlogo图片地址
*@paramneedCompress是否压缩logo图片大小
*@return
*@throwsException参数说明
*@returnBufferedImage返回类型
*@throws
*/
privatestaticBufferedImagecreateImage(Stringcontent,StringlogoPath,booleanneedCompress)throwsException{
Hashtable<EncodeHintType,Object>hints=newHashtable<EncodeHintType,Object>();
hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET,CHARSET);
hints.put(EncodeHintType.MARGIN,1);
BitMatrixbitMatrix=newMultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,QRCODE_SIZE,QRCODE_SIZE,hints);
intwidth=bitMatrix.getWidth();
intheight=bitMatrix.getHeight();
BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
for(intx=0;x<width;x++){
for(inty=0;y<height;y++){
image.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
}
}
if(logoPath==null||"".equals(logoPath)){
returnimage;
}
//插入logo
QRCodeUtil.insertImage(image,logoPath,needCompress);
returnimage;
}
/**
*@Title:insertImage
*@Description:将logo插入到二维码中
*@paramsource二维码Image流
*@paramimgPathlogo地址
*@paramneedCompress是否压缩大小
*@throwsException参数说明
*@returnvoid返回类型
*@throws
*/
privatestaticvoidinsertImage(BufferedImagesource,StringlogoPath,booleanneedCompress)throwsException{
Filefile=newFile(logoPath);
if(!file.exists()){
System.err.println(""+logoPath+"该文件不存在!");
return;
}
Imagesrc=ImageIO.read(newFile(logoPath));
intwidth=src.getWidth(null);
intheight=src.getHeight(null);
if(needCompress){//压缩LOGO
if(width>LOGO_WIDTH){
width=LOGO_WIDTH;
}
if(height>LOGO_HEIGHT){
height=LOGO_HEIGHT;
}
Imageimage=src.getScaledInstance(width,height,Image.SCALE_SMOOTH);
BufferedImagetag=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphicsg=tag.getGraphics();
g.drawImage(image,0,0,null);//绘制缩小后的图
g.dispose();
src=image;
}
//插入LOGO
Graphics2Dgraph=source.createGraphics();
intx=(QRCODE_SIZE-width)/2;
inty=(QRCODE_SIZE-height)/2;
graph.drawImage(src,x,y,width,height,null);
Shapeshape=newRoundRectangle2D.Float(x,y,width,width,6,6);
graph.setStroke(newBasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
*@Title:mkdirs
*@Description:创建文件夹
*@paramdestPath文件夹地址
*@returnvoid返回类型
*@throws
*/
privatestaticbooleanmkdirs(StringdestPath){
Filefile=newFile(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if(!file.exists()&&!file.isDirectory()){
file.mkdirs();
returntrue;
}
returnfalse;
}
/**
*@Title:encode
*@Description:生成二维码
*@paramcontent二维码内容
*@paramimgPathlogo图片地址
*@paramdestPath目标保存地址
*@paramneedCompress是否压缩logo图片大小
*@throwsException参数说明
*@returnvoid返回类型
*@throws
*/
privatestaticvoidencode(Stringcontent,StringlogoPath,StringdestPath,booleanneedCompress)throwsException{
BufferedImageimage=QRCodeUtil.createImage(content,logoPath,needCompress);
if(mkdirs(destPath)){
Stringfile=newRandom().nextInt(99999999)+".jpg";
ImageIO.write(image,FORMAT_NAME,newFile(destPath+"/"+file));
}
}
/**
*@Title:encode
*@Description:生成二维码
*@paramcontent二维码内容
*@paramdestPath目标保存地址
*@throwsException参数说明
*@returnvoid返回类型
*@throws
*/
publicstaticvoidencode(Stringcontent,StringdestPath)throwsException{
QRCodeUtil.encode(content,null,destPath,false);
}
/**
*@Title:encode
*@Description:生成二维码
*@paramcontent二维码内容
*@paramimgPathlogo图片地址
*@paramoutput输出流
*@paramneedCompress是否压缩logo图片大小
*@throwsException参数说明
*@returnvoid返回类型
*@throws
*/
publicstaticvoidencode(Stringcontent,StringlogoPath,OutputStreamoutput,booleanneedCompress)throwsException{
BufferedImageimage=QRCodeUtil.createImage(content,logoPath,needCompress);
ImageIO.write(image,FORMAT_NAME,output);
}
/**
*@Title:encode
*@Description:生成二维码
*@paramcontent二维码内容
*@paramoutput输出流
*@throwsException参数说明
*@returnvoid返回类型
*@throws
*/
publicstaticvoidencode(Stringcontent,OutputStreamoutput)throwsException{
QRCodeUtil.encode(content,null,output,false);
}
/**
*@Title:decode
*@Description:对二维码解码
*@paramfile文件对象
*@return解码后的二维码内容字符串
*@throwsException参数说明
*@returnString返回类型
*@throws
*/
privatestaticStringdecode(Filefile)throwsException{
BufferedImageimage;
image=ImageIO.read(file);
if(image==null){
returnnull;
}
BufferedImageLuminanceSourcesource=newBufferedImageLuminanceSource(image);
BinaryBitmapbitmap=newBinaryBitmap(newHybridBinarizer(source));
Hashtable<DecodeHintType,String>hints=newHashtable<DecodeHintType,String>();
hints.put(DecodeHintType.CHARACTER_SET,CHARSET);
returnnewMultiFormatReader().decode(bitmap,hints).getText();
}
/**
*@Title:decode
*@Description:对二维码解码
*@parampath文件路径
*@return
*@throwsException参数说明
*@returnString返回类型
*@throws
*/
publicstaticStringdecode(Stringpath)throwsException{
returnQRCodeUtil.decode(newFile(path));
}
}
QRCodeServlet.java
packagecom.webos.servlet;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.webos.util.QRCodeUtil;
/*
*ServletimplementationclassQRCodeServlet
*/
@WebServlet("/QRCodeServlet")
publicclassQRCodeServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
/*
*@seeHttpServlet#HttpServlet()
*/
publicQRCodeServlet(){
super();
}
/*
*@seeHttpServlet#doGet(HttpServletRequestrequest,HttpServletResponse
*response)
*/
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
try{
Stringtext="http://www.baidu.com?timestamp="+System.currentTimeMillis();
QRCodeUtil.encode(text,response.getOutputStream());
}catch(Exceptione){
e.printStackTrace();
}
}
/*
*@seeHttpServlet#doPost(HttpServletRequestrequest,HttpServletResponse
*response)
*/
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
//TODOAuto-generatedmethodstub
doGet(request,response);
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!