java--实现将文字生成二维码图片,并在中间附上logo,下方附上文字
前段时间因为工作需要,要实现将一段文字或者url生成二维码,然后中间附上logo,下方正中间附上文字的功能。
上网找了几篇教程学习了下,由于没有保存借鉴的博文链接,所以就没po上参考文章的链接啦,感谢几位博主的分享~
大概的实现效果如下图所示:
实现步骤:
(1)导入java_ZXing_jar包,点此下载jar包
(2)编写画二维码代码
package QRCode; import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
} public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
} }
MatrixToImageWriter
(3)编写一个类,用来设置中间logo的属性(注:代码中“照片的1/6”,应该是“二维码图片的1/6”,懒得重新上传代码,特此注释下)
package QRCode; import java.awt.Color; public class LogoConfig {
// logo默认边框颜色
public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
// logo默认边框宽度
public static final int DEFAULT_BORDER = 2;
// logo大小默认为照片的1/6
public static final int DEFAULT_LOGOPART = 6; private final int border = DEFAULT_BORDER;
private final Color borderColor;
private final int logoPart; /**
* Creates a default config with on color {@link #BLACK} and off color
* {@link #WHITE}, generating normal black-on-white barcodes.
*/
public LogoConfig()
{
this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
} public LogoConfig(Color borderColor, int logoPart)
{
this.borderColor = borderColor;
this.logoPart = logoPart;
} public Color getBorderColor()
{
return borderColor;
} public int getBorder()
{
return border;
} public int getLogoPart()
{
return logoPart;
}
}
LogoConfig
(4)为二维码图片添加logo
/**
* 给二维码图片添加Logo
*
* @param qrPic
* @param logoPic
*/
public static void addLogo_QRCode(File qrPic, File logoPic, LogoConfig logoConfig)
{
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(); ImageIO.write(image, "jpeg", new File("D:/newPic.jpg"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
addLogo_QRCode
(5)为添加好logo的二维码图片添加文字
/**
* @为图片添加文字
* @param pressText 文字
* @param newImg 带文字的图片
* @param targetImg 需要添加文字的图片
* @param fontStyle
* @param color
* @param fontSize
* @param width
* @param heigh
*/
public static void pressText(String pressText, String newImg, String targetImg, int fontStyle, Color color, int fontSize, int width, int height) { //计算文字开始的位置
//x开始的位置:(图片宽度-字体大小*字的个数)/2
int startX = (width-(fontSize*pressText.length()))/2;
//y开始的位置:图片高度-(图片高度-图片宽度)/2
int startY = height-(height-width)/2; 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(); FileOutputStream out = new FileOutputStream(newImg);
ImageIO.write(image, "JPEG", out);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
System.out.println("image press success");
} catch (Exception e) {
System.out.println(e);
}
}
pressText
(6)上面功能写好后,可以综合一下进行测试
public static void main(String args[]) {
try {
//二维码表示的内容
String content = "http://www.cnblogs.com/"; //存放logo的文件夹
String path = "E:/QRCodeImage"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); @SuppressWarnings("rawtypes")
Map hints = new HashMap(); //设置UTF-8, 防止中文乱码
hints.put(EncodeHintType.CHARACTER_SET, "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 = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints); //qrcFile用来存放生成的二维码图片(无logo,无文字)
File qrcFile = new File(path,"myPicture.jpg");
//logoFile用来存放带有logo的二维码图片(二维码+logo,无文字)
File logoFile = new File(path,"logo.jpg"); //开始画二维码
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", qrcFile); //在二维码中加入图片
LogoConfig logoConfig = new LogoConfig(); //LogoConfig中设置Logo的属性
addLogo_QRCode(qrcFile, logoFile, logoConfig); int font = 18; //字体大小
int fontStyle = 1; //字体风格 //用来存放带有logo+文字的二维码图片
String newImageWithText = "D:/imageWithText.jpg";
//带有logo的二维码图片
String targetImage = "D:/newPic.jpg";
//附加在图片上的文字信息
String text = "文字测试一二三四五六123"; //在二维码下方添加文字(文字居中)
pressText(text, newImageWithText, targetImage, fontStyle, Color.BLUE, font, width, height) ; } catch (Exception e) {
e.printStackTrace();
}
}
main
注意:部分ZXing的jar包导入后,配置EncodeHintType.MARGIN会报错
使用上面附上的java_ZXing_jar包即可。
分享就到此结束啦~~
java--实现将文字生成二维码图片,并在中间附上logo,下方附上文字的更多相关文章
- JAVA根据URL生成二维码图片、根据路径生成二维码图片
引入jar包 zxing-2.3.0.jar.IKAnalyzer2012_u6.jar 下载地址:https://yvioo.lanzous.com/b00nlbp6h ...
- JAVA生成二维码图片代码
首先需要导入 QRCode.jar 包 下载地址看这里 http://pan.baidu.com/s/1o6qRFqM import java.awt.Color;import java.awt. ...
- java生成二维码图片
1.POM文件引入 <dependency> <groupId>com.google.zxing</groupId> <artifactId>core& ...
- Node.js在指定的图片模板上生成二维码图片并附带底部文字说明
在Node.js中,我们可以通过qr-image包直接在后台生成二维码图片,使用方法很简单: var qr = require('qr-image'); exports.createQRImage = ...
- phpqrcode生成带logo的二维码图片及带文字的二维码图片
<?php require_once "./phpqrcode/phpqrcode.php"; /** * 这样就可以生成二维码了,实际上在png这个方法里还有几个参数需要使 ...
- 【java工具类】生成二维码
/** * 生成二维码图片 * @param text 扫描二维码后跳转的url * @param width 图片宽度 * @param height 图片高度 * @param filePath ...
- 使用python调用zxing库生成二维码图片
(1) 安装Jpype 用python调用jar包须要安装jpype扩展,在Ubuntu上能够直接使用apt-get安装jpype扩展 $ sudo apt-get install pytho ...
- js 生成二维码图片
1.用纯JavaScript实现的微信二维码图片生成器 QRCode.js是javascript实现二维码(QRCode)制作生成库. QRCode.js有着良好的跨浏览器兼容性(高版本使用HTML5 ...
- 使用google zxing生成二维码图片
生成二维码工具类: 1 import java.awt.geom.AffineTransform; 2 import java.awt.image.AffineTransformOp; 3 impor ...
随机推荐
- Liferay7 BPM门户开发之35: AssetTag的集成查询
Tag是liferay中的Asset特性,可以用来对信息进行分类,在iferay中的Asset类型为: 1. Web Content(自定义内容) 2. Documents and Media(文档库 ...
- ES6类与模块
class Animal { // 构造方法,实例化的时候会被调用,如果不指定,那么会有一个不带参数的默认构造函数 constructor(name, color) { this.name = nam ...
- SqlServer2008R2用Windows身份登录18456错误解决
// 重装系统后发现SqlServer2008R2使用Windows身份验证不能进行连接,如下图: 以前经常会碰到SqlServer 身份验证连接失败,Windows身份验证的连接失败还是第一次,试了 ...
- 谢谢博客-园,让我不再有开源AYUI的想法
第一次 第二次 教程不会在博客园上写了,具体的看我官网博客吧,谢谢大家了 ================= 我是个有素质的程序员 艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹艹 ...
- 【组合数学+动态规划】在如下8*6的矩阵中,请计算从A移动到B一共有____种走法。要求每次只能向上或向右移动一格,并且不能经过P。
在如下8*6的矩阵中,请计算从A移动到B一共有__种走法.要求每次只能向上或向右移动一格,并且不能经过P. A:456 B:492 C:568 D:626 E:680 F:702 解析: 8*6的矩阵 ...
- Codeforces Round #382 (Div. 2) D. Taxes 哥德巴赫猜想
D. Taxes 题目链接 http://codeforces.com/contest/735/problem/D 题面 Mr. Funt now lives in a country with a ...
- Redis之高可用方案
Redis之高可用方案 Redis以其高效的访问速度著称.但由于官方还未发布redis-cluster,而redis的replica又有诸多不便:比如一组master-slave的机器,如果之间有 ...
- 【卡西欧Fx-5800p】市场分析 ppt
一.ppt视频 二.大概内容 1:2010年的4万亿救市政策和 2011年4月后财政收缩政策 2:2011-7-23温州动车追尾事故70%的公路高铁等基础建设项目停缓建 ·····
- 定时从远程的数据库中取数据,然后把取出来的数据插入或更新本地的oracle数据库的表
最近项目中有一种需求: 大致需求是这样的 通过给定的 用户名和密码 要定时从远程的数据库中取数据,然后把取出来的数据插入或更新本地的oracle数据库的表 项目的结构式struts1 hibernat ...
- Navi.Soft30.框架.WebMVC.开发手册
1概述 1.1应用场景 互联网高速发展,互联网软件也随之越来越多,Web程序越来越被广泛使用.它部署简单,维护方便,深得众多软件公司使用 Bootstrap前端框架,是最近非常流行的框架之一.它简洁, ...