利用Java生成带有文字的二维码
介绍
主要使用了goole的zxing包,下面给出了示例代码,很方便大家的理解和学习,代码都属于初步框架,功能有了,需要根据实际使用情况完善优化。
第一步、maven导入zxing
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.2.1</version> </dependency>
第二步、开始生成二维码:
privatestaticfinalintBLACK=0xFF000000;
privatestaticfinalintWHITE=0xFFFFFFFF;
/**
*把生成的二维码存入到图片中
*@parammatrixzxing包下的二维码类
*@return
*/
publicstaticBufferedImagetoBufferedImage(BitMatrixmatrix){
intwidth=matrix.getWidth();
intheight=matrix.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,matrix.get(x,y)?BLACK:WHITE);
}
}
returnimage;
}
/**
*生成二维码并写入文件
*@paramcontent扫描二维码的内容
*@paramformat图片格式jpg
*@paramfile文件
*@throwsException
*/
publicstaticvoidwriteToFile(Stringcontent,Stringformat,Filefile)
throwsException{
MultiFormatWritermultiFormatWriter=newMultiFormatWriter();
@SuppressWarnings("rawtypes")
Maphints=newHashMap();
//设置UTF-8,防止中文乱码
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
//设置二维码四周白色区域的大小
hints.put(EncodeHintType.MARGIN,1);
//设置二维码的容错性
hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
//画二维码
BitMatrixbitMatrix=multiFormatWriter.encode(content,BarcodeFormat.QR_CODE,WIDTH,HEIGHT,hints);
BufferedImageimage=toBufferedImage(bitMatrix);
if(!ImageIO.write(image,format,file)){
thrownewIOException("Couldnotwriteanimageofformat"+format+"to"+file);
}
}
第三步、把文字写入二维码图片中:
/**
*给二维码图片加上文字
*@parampressText文字
*@paramqrFile二维码文件
*@paramfontStyle
*@paramcolor
*@paramfontSize
*/
publicstaticvoidpressText(StringpressText,FileqrFile,intfontStyle,Colorcolor,intfontSize)throwsException{
pressText=newString(pressText.getBytes(),"utf-8");
Imagesrc=ImageIO.read(qrFile);
intimageW=src.getWidth(null);
intimageH=src.getHeight(null);
BufferedImageimage=newBufferedImage(imageW,imageH,BufferedImage.TYPE_INT_RGB);
Graphicsg=image.createGraphics();
g.drawImage(src,0,0,imageW,imageH,null);
//设置画笔的颜色
g.setColor(color);
//设置字体
Fontfont=newFont("宋体",fontStyle,fontSize);
FontMetricsmetrics=g.getFontMetrics(font);
//文字在图片中的坐标这里设置在中间
intstartX=(WIDTH-metrics.stringWidth(pressText))/2;
intstartY=HEIGHT/2;
g.setFont(font);
g.drawString(pressText,startX,startY);
g.dispose();
FileOutputStreamout=newFileOutputStream(qrFile);
ImageIO.write(image,"JPEG",out);
out.close();
System.out.println("imagepresssuccess");
}
第四步、在main方法中测试一下,一个中间带文字的二维码就生成了
publicstaticvoidmain(String[]args)throwsException{
FileqrcFile=newFile("/Users/deweixu/","google.jpg");
writeToFile("www.google.com.hk","jpg",qrcFile);
pressText("谷歌",qrcFile,5,Color.RED,32);
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。