前段时间没事突然看到有些宣传海报上面打印了带log的二维码,于是在网上查找了生成二维码的方法,自己进行了写修改,下面直接贴出代码供参考:
注:要引入QRCode.jar包
1、这是生成二维码的处理类:QRCodeEncoderHandler
package com.czp.commonutil;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.czp.QRCode.pro.TwoDimensionCodeImage;
import com.czp.logQRcode.LogoConfig;
import com.czp.logQRcode.MatrixToImageWriter;
import com.czp.util.CommonUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
public class QRCodeEncoderHandler {
/**
* 生成二维码(QRCode)图片的公共方法
* @param content 存储内容
* @param imgType 图片类型
* @param size 二维码尺寸
* @param addLog 是否添加log
* @param addText 添加的文字
* @return
*/
@SuppressWarnings("unchecked")
public synchronized static String qRCodeCommon(String content, String imgType, int size,Boolean addLog,String addText) {
final String uploadRootDir="D:/temp/";//临时文件夹
final String uploadPathImg="D:/imgfile";//存储文件夹
final String path = "E:/QRCodeImage";//存放logo的文件夹
String fileDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
String name=CommonUtil.getSysFormatTime("yyyyMMddHHmmssSSS").toString();//图片名称
final String uploadPath =uploadPathImg+ "/"+fileDate+"/";//+priBankCode+"/"
BufferedImage bufImg = null;
String fileNamePath=uploadPath+"";//返回生成二维码路径、名称
int imgSize=1;
//size = 2;
try {
Qrcode qrcodeHandler = new Qrcode();
// 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
qrcodeHandler.setQrcodeErrorCorrect('M');
qrcodeHandler.setQrcodeEncodeMode('B');
// 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
qrcodeHandler.setQrcodeVersion(size);
// 获得内容的字节数组,设置编码格式
byte[] contentBytes = content.getBytes("utf-8");
// 图片尺寸
imgSize = 67 + 12 * size;
System.out.println("imgSize:"+imgSize);
bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufImg.createGraphics();
// 设置背景颜色
gs.setBackground(Color.WHITE);
gs.clearRect(0, 0, imgSize, imgSize);
// 设定图像颜色> BLACK
gs.setColor(Color.BLACK);
// 设置偏移量,不设置可能导致解析出错
int pixoff = 2;
// 输出内容> 二维码
if (contentBytes.length > 0 && contentBytes.length < 200) {
boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
for (int i = 0; i < codeOut.length; i++) {
for (int j = 0; j < codeOut.length; j++) {
if (codeOut[j][i]) {
gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
}
}
}
} else {
System.out.println("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
}
gs.dispose();
bufImg.flush();
} catch (Exception e) {
e.printStackTrace();
}
File uploadDir = new File(uploadPath);
if(!uploadDir.exists()){
uploadDir.mkdirs();
}
if(addLog && ""!=addText ) {//当要同时写入log和文字
//storageQRCodeIMG(bufImg,uploadRootDir,name+"_Temp.PNG");//将生成二维码图片存入临时文件夹
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置UTF-8, 防止中文乱码
hints.put(EncodeHintType.MARGIN,1); //设置二维码四周白色区域的大小
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置二维码的容错性
//width:图片完整的宽;height:图片完整的高
//因为要在二维码下方附上文字,所以把图片设置为长方形(高大于宽)
// int width = 400;
// int height = 450;
//画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
BitMatrix bitMatrix=null;
try {
bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//qrcFile用来存放生成的二维码图片(无logo,无文字)
File qrcFile = new File(uploadRootDir,name+"_Temp.PNG");
//logoFile用来存放带有logo的图片
File logoFile = new File(path,"QQ.PNG");//log图片
//开始画二维码
try {
MatrixToImageWriter.writeToFile(bitMatrix, "PNG", qrcFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//在二维码中加入图片
LogoConfig logoConfig = new LogoConfig(); //LogoConfig中设置Logo的属性
addLogo_QRCode(qrcFile, logoFile, logoConfig,uploadRootDir,name+"_imageWithLogTemp.PNG");//向生成的二维码图片加入log,并写入临时文件夹
//用来存放带有logo+文字的二维码图片的路径
String withLogAndTextName =name+ "_imageWithText.PNG";
//带有logo的二维码图片
String targetImage = uploadRootDir+name+"_imageWithLogTemp.PNG";
pressText(addText,targetImage, 1,Color.BLUE, 10, imgSize, imgSize, uploadPath,withLogAndTextName);
fileNamePath+=withLogAndTextName;
// new File(uploadRootDir+name).delete();//删除原先的图片
}else if(!addLog && ""!=addText) {//只添加文字时
//storageQRCodeIMG(bufImg,uploadRootDir,name+"_Temp.PNG");//将生成二维码图片存入临时文件夹
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置UTF-8, 防止中文乱码
hints.put(EncodeHintType.MARGIN,1); //设置二维码四周白色区域的大小
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置二维码的容错性
//width:图片完整的宽;height:图片完整的高
//因为要在二维码下方附上文字,所以把图片设置为长方形(高大于宽)
//int width = 400;
// int height = 450;
//画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
BitMatrix bitMatrix=null;
try {
bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//qrcFile用来存放生成的二维码图片(无logo,无文字)
File qrcFile = new File(uploadRootDir,name+"_Temp.PNG");
//开始画二维码
try {
MatrixToImageWriter.writeToFile(bitMatrix, "PNG", qrcFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//用来存放带有logo+文字的二维码图片的路径
String withTextName =name+ "_withText.PNG";
//生成的二维码图片
String targetImage = uploadRootDir+name+"_Temp.PNG";
pressText(addText,targetImage, 1,Color.BLUE, 18, imgSize, imgSize, uploadPath,withTextName);
fileNamePath+=withTextName;
}else if(addLog && ""==addText){//只添加log图片
//storageQRCodeIMG(bufImg,uploadRootDir,name+"_Temp.PNG");//将生成二维码图片存入临时文件夹
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置UTF-8, 防止中文乱码
hints.put(EncodeHintType.MARGIN,1); //设置二维码四周白色区域的大小
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置二维码的容错性
//width:图片完整的宽;height:图片完整的高
//因为要在二维码下方附上文字,所以把图片设置为长方形(高大于宽)
//int width = 400;
// int height = 450;
//画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
BitMatrix bitMatrix=null;
try {
bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//qrcFile用来存放生成的二维码图片(无logo,无文字)
File qrcFile = new File(uploadRootDir,name+"_Temp.PNG");
//logoFile用来存放带有logo的图片
File logoFile = new File(path,"QQ.PNG");//log图片
//开始画二维码
try {
MatrixToImageWriter.writeToFile(bitMatrix, "PNG", qrcFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//用来存放生成二维码的路径
String WithLogName =name+"_imageWithLog.PNG";
//在二维码中加入图片
LogoConfig logoConfig = new LogoConfig(); //LogoConfig中设置Logo的属性
addLogo_QRCode(qrcFile, logoFile, logoConfig,uploadPath,WithLogName);//向生成的二维码图片加入log
fileNamePath+=WithLogName;
}else if(!addLog && ""==addText) {//只生成二维码
storageQRCodeIMG(bufImg,uploadPath,name+".PNG");//将生成二维码图片存入文件夹
fileNamePath+=name+".PNG";
}
return fileNamePath;
}
/**
* 存储二维码至指定路径(storageQRCodeIMG)
* @param bufImg 图片
* @param path 图片路径
* @param name 图片名称
*/
public static void storageQRCodeIMG(BufferedImage bufImg,String path,String name) {
if(".PNG".lastIndexOf(name)!=-1 || ".png".lastIndexOf(name)!=-1) {
name=name+".PNG";
}
File imgFile = new File(path+name);
// 生成二维码QRCode图片
try {
ImageIO.write(bufImg, "PNG", imgFile);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解析二维码(QRCode)
* @param imgPath 图片路径
* @return
*/
public String decoderQRCode(String imgPath) {
// QRCode 二维码图片的文件
File imageFile = new File(imgPath);
BufferedImage bufImg = null;
String content = null;
try {
bufImg = ImageIO.read(imageFile);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
}
/**
* 给二维码图片添加Logo
*
* @param qrPic 要添加log的二维码
* @param logoPic log图片
*@param logoConfig log参数
*@param newImgPath 新生成图片存储路径
*@param newImgName 新生成图片名称
*/
public static void addLogo_QRCode(File qrPic, File logoPic, LogoConfig logoConfig,String newImgPath,String newImgName)
{
try
{
if (!qrPic.isFile() || !logoPic.isFile())
{
System.out.print("file not find !");
System.exit(0);
}
/**
* 读取二维码图片,并构建绘图对象
*/
BufferedImage image = ImageIO.read(qrPic);
Graphics2D g = image.createGraphics();
/**
* 读取Logo图片
*/
BufferedImage logo = ImageIO.read(logoPic);
int widthLogo = image.getWidth()/logoConfig.getLogoPart();
// int heightLogo = image.getHeight()/logoConfig.getLogoPart();
int heightLogo = image.getWidth()/logoConfig.getLogoPart(); //保持二维码是正方形的
// 计算图片放置位置
int x = (image.getWidth() - widthLogo) / 2;
int y = (image.getHeight() - heightLogo) / 2 ;
//开始绘制图片
g.drawImage(logo, x, y, widthLogo, heightLogo, null);
g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
g.setStroke(new BasicStroke(logoConfig.getBorder()));
g.setColor(logoConfig.getBorderColor());
g.drawRect(x, y, widthLogo, heightLogo);
g.dispose();
image.flush();
//将加入log的图片写入指定路径
storageQRCodeIMG(image,newImgPath,newImgName);
// ImageIO.write(image, "PNG", new File("D:/newPic.PNG"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* @为图片添加文字
* @param pressText 文字
* @param targetImg 需要添加文字的图片
* @param fontStyle 需要添加文字的字体风格
* @param color 字体颜色
* @param fontSize 字体大小
* @param width 生成图片宽度
* @param heigh 生成图片高度
* @param newImgPath 新生成的图片存储路径
* @param newImgName 新生成的图片名称
*/
public static void pressText(String pressText,String targetImg, int fontStyle, Color color, int fontSize, int width, int height,String newImgPath ,String newImgName) {
//设置一个默认长度和宽度
// width = 400;
// height = 450;
//计算文字开始的位置
//x开始的位置:(图片宽度-字体大小*字的个数)/2
int startX = (width-(fontSize*pressText.length()))/2;
//y开始的位置:图片高度-(图片高度-图片宽度)/2
int startY = height-(height-width)/2-5;
try {
File file = new File(targetImg);
Image src = ImageIO.read(file);
int imageW = src.getWidth(null);
int imageH = src.getHeight(null);
BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, imageW, imageH, null);
g.setColor(color);
g.setFont(new Font(null, fontStyle, fontSize));
g.drawString(pressText, startX, startY);
g.dispose();
image.flush();
//将加入文字的图片写入指定路径
storageQRCodeIMG(image,newImgPath,newImgName);
/*FileOutputStream out = new FileOutputStream(newImg);
ImageIO.write(image, "PNG", out);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();*/
System.out.println("image press success");
} catch (Exception e) {
System.out.println(e);
}
}
}
2、下面是测试类:
package com.czp.QRCodeTest;
import com.czp.commonutil.QRCodeEncoderHandler;
public class testQRCode {
public static void main(String[] args) {
/*File fileDir = new File("D:/imgfile/");
fileDir.mkdirs(); */
QRCodeEncoderHandler qr=new QRCodeEncoderHandler();
//BufferedImage BIM=qr.qRCodeCommon("xx很帅!哈哈。。。","PNG",5,true,"");
//TwoDimensionCode TDC=new TwoDimensionCode();
//String pathName1=qr.qRCodeCommon("xx很帅!哈哈。。。","PNG",5,false,"");//只生成带二维码
//String pathName2=qr.qRCodeCommon("xx很帅!哈哈。。。","PNG",5,true,"");//只生成带log的
String pathName3=qr.qRCodeCommon("408120","PNG",18,true,"仙女专用");//只生成带log和文字的
//String pathName4=qr.qRCodeCommon("xx很帅!哈哈。。。","PNG",5,false,"123测试");//只生成带文字的
//System.out.println("pathName1:"+pathName1);
//System.out.println("pathName2:"+pathName2);
System.out.println("pathName3:"+pathName3);
//System.out.println("pathName4:"+pathName4);
//System.out.println("二维码信息:"+TDC.decoderQRCode("D:/imgfile/20171110172958.png"));//进行二维码信息的解析
//System.out.println(BIM.toString());
}
}
3、下面是生成的二维码示例: