您的位置:首页 > 编程语言 > Go语言

生成二维码(QRCode)图片加LOGO

2017-12-18 16:13 330 查看
package com.konland.web;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import com.swetake.util.Qrcode;

/**
* 生成二维码(QRCode)图片
* @author GYF
* @date 2017年12月18日 下午15:43:17
* @version 1.0
*/

public class LogoQrCode {

/**
* 生成二维码(QRCode)图片
* @param content 二维码图片的内容
* @param imgPath  存放生成二维码图片完整的路径
* @param logoPath  二维码图片中间的logo路径
* @param type  生成的图片后缀
*/
public static String createQRCode(String content, String imgPath,String logoPath, int version,String type) {
try {
if(StringUtils.isNotBlank(imgPath)){
return "保存图片的路径未不存在";
}else if(StringUtils.isNotBlank(logoPath)){
return "保存图片的路径未不存在";
}else if(StringUtils.isNotBlank(content)){
return "二维码内容为空";
}
Qrcode qrcodeHandler = new Qrcode();
// 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
qrcodeHandler.setQrcodeErrorCorrect('Q');
// N代表数字,A代表字符a-Z,B代表其他字符
qrcodeHandler.setQrcodeEncodeMode('B');
// 设置设置二维码版本,取值范围1-40,值越大尺寸越大,可存储的信息越大
qrcodeHandler.setQrcodeVersion(version);
// 图片尺寸
int imgSize = 67 + 12 * (version - 1);
byte[] contentBytes = content.getBytes("gb2312");
BufferedImage image = new BufferedImage(imgSize, imgSize,
BufferedImage.TYPE_INT_RGB);
Graphics2D gs = image.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 < 130) {
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 {
return "QRCode content bytes length ="+contentBytes.length + " not in [ 0,125]";
}
// 实例化一个Image对象。
Image logo = ImageIO.read(new File(logoPath));
int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image
.getWidth() * 2 / 10) : logo.getWidth(null), heightLogo = logo
.getHeight(null) > image.getHeight() * 2 / 10 ? (image
.getHeight() * 2 / 10) : logo.getWidth(null);
/**
* logo放在中心
*/
int x = (image.getWidth() - widthLogo) / 2;
int y = (image.getHeight() - heightLogo) / 2;
gs.drawImage(logo, x, y, widthLogo, heightLogo, null);
gs.dispose();
image.flush();
// 生成二维码QRCode图片
File imgFile = new File(imgPath);
ImageIO.write(image,type, imgFile);

} catch (Exception e) {
e.printStackTrace();
return "error";
}
return "success";
}

public static void main(String[] args) {
String imgPath = "E:\\code\\"+new Date().getTime()+".jpg";
String logoPath = "E:\\code\\logo.png";
String encoderContent = "https://www.baidu.com/";
LogoQrCode.createQRCode(encoderContent, imgPath, logoPath, 6,"jpg");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二维码 图片