Java 生成微信扫描的二维码,跳转到指定网址,图片增加二维码及文字水印
两种场景:
1、图片海报中加二维码
2、二维码中间加入指定图标
注意点:字体要再设置一下清晰度,要不特别模糊。
graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
/*** @description 二维码控制器*/
@RestController
public class QrcodeController {@AutowiredResourceLoader resourceLoader;/*** todo 每个用户一张二维码,里面的信息就是邀请码或者是userid** @param userid MREAM5* @return void* @description 生成二维码* @Param response**/@GetMapping("/getQrcode")@ResponseBodypublic void getQrcode(@RequestParam("userid") String userid, HttpServletResponse response) throws Exception {String url = "http://www.biturd.com/pages/register/register";String inviteCode = getInviteCodeByUserId(userid);String content = url + "?invite_code=" + inviteCode;
//
// String imgPath = "./test.jpg";Resource resource = resourceLoader.getResource("classpath:test.jpg");File imgFile = resource.getFile();// 海报图片BufferedImage outerImg = ImageIO.read(imgFile);Boolean needCompress = true;//图片海报outerImg中加二维码ByteArrayOutputStream out = QRCodeUtil.encodeIOWith(content, outerImg, needCompress);//二维码中间加图片ByteArrayOutputStream out2 = QRCodeUtil.encodeIO(content, imgFile.getPath(), needCompress);//返回二维码response.setCharacterEncoding("UTF-8");response.setContentType("image/jpeg;charset=UTF-8");response.setContentLength(out.size());ServletOutputStream outputStream = response.getOutputStream();outputStream.write(out.toByteArray());outputStream.flush();outputStream.close();}private String getInviteCodeByUserId(String userid) {return "ANGYS1";}}
package com.biturd.manghejava.utils;import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.awt.SunHints;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;// https://uutool.cn/img-coord/
// https://blog.csdn.net/qq_38377774/article/details/108767573
// https://blog.csdn.net/weixin_39220472/article/details/120888956?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0.pc_relevant_default&spm=1001.2101.3001.4242.1&utm_relevant_index=3
public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 80;// LOGO高度private static final int HEIGHT = 80;// LOGO宽度private static final int LEFT = 225;// LOGO高度private static final int UP = 475;// 288 535private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {Map<EncodeHintType, Object> hints = new ConcurrentHashMap();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);int width = bitMatrix.getWidth();int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, imgPath, needCompress);return image;}private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println("" + imgPath + " 该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 绘制缩小后的图g.dispose();src = image;}// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);mkdirs(destPath);ImageIO.write(image, FORMAT_NAME, new File(destPath));}public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);return image;}public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath) throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}public static byte[] getQRCodeImage(String content) throws WriterException, IOException {QRCodeWriter qrCodeWriter = new QRCodeWriter();BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE);ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();MatrixToImageWriter.writeToStream(bitMatrix, FORMAT_NAME, pngOutputStream);byte[] pngData = pngOutputStream.toByteArray();return pngData;}public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);ImageIO.write(image, FORMAT_NAME, output);}public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.encode(content, null, output, false);}public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}//二维码中间有图片public static ByteArrayOutputStream encodeIO(String content, String imgPath, Boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath,needCompress);//创建储存图片二进制流的输出流ByteArrayOutputStream baos = new ByteArrayOutputStream();//将二进制数据写入ByteArrayOutputStreamImageIO.write(image, "jpg", baos);return baos;}private static BufferedImage createFromImage(String content, BufferedImage outer, boolean needCompress) throws Exception {Map<EncodeHintType, Object> hints = new ConcurrentHashMap();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);int width = bitMatrix.getWidth();int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}// 插入图片QRCodeUtil.insertFromImage(outer, image, needCompress);return outer;}private static void insertFromImage(BufferedImage src,BufferedImage qrCode, boolean needCompress) throws Exception {Image image = null;int width = qrCode.getWidth(null);int height = qrCode.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}image = qrCode.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 绘制缩小后的图g.dispose();}//左上 256 500 右下 290 535// 插入LOGOGraphics2D graph = src.createGraphics();graph.drawImage(image, LEFT, UP, null);graph.setColor(Color.WHITE);graph.dispose();}////图片中间有二维码public static ByteArrayOutputStream encodeIOWith(String content, BufferedImage outer, Boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createFromImage(content, outer,needCompress);addText(image, content);//创建储存图片二进制流的输出流ByteArrayOutputStream baos = new ByteArrayOutputStream();//将二进制数据写入ByteArrayOutputStreamImageIO.write(image, "jpg", baos);return baos;}public static void addText(BufferedImage image,String text){Graphics2D graph = image.createGraphics();
// graph.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);// 5、设置水印文字颜色graph.setColor(Color.black);graph.setFont(new Font("宋体", Font.BOLD, 15));// 文字增加清晰度graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);graph.drawString("邀请码:", 240, 450);graph.drawString(text, 220, 470);graph.dispose();}
}
Java 生成微信扫描的二维码,跳转到指定网址,图片增加二维码及文字水印相关推荐
- Java生成微信小程序二维码
Java生成微信小程序二维码 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.Byt ...
- Java企业微信会话存档开发(从跳坑到爬坑)
Java企业微信会话存档开发(从跳坑到爬坑) 本文仅作为方便首次开发企业微信使用 文章目录 Java企业微信会话存档开发(从跳坑到爬坑) 前言 一.开发准备 1.企业微信后台配置 2.sdk下载 3. ...
- Java生成微信小程序二维码、上传至阿里云OSS
依赖 <!-- 阿里云oss依赖 --><dependency><groupId>com.aliyun.oss</groupId><artifac ...
- Java生成微信小程序二维码,5种实现方式,一个比一个简单
文章目录 前言 先看官网 一.JDK自带的URLConnection方式 二.Apache的HttpClient方式 三.okhttp3方式 四.Unirest方式 五.RestTemplate方式 ...
- 【java】Java生成微信小程序二维码
文章目录 前言 应用场景 微信小程序官网 1.RestTemplate方式 核心代码 getAccessToken 2. Unirest方式 Maven依赖 核心代码 3. okhttp3方式 Mav ...
- 魔众一物一码溯源防伪系统 v1.2.0 增加二维码显示页面,后台升级
魔众一物一码溯源防伪系统支持批量生成.管理防伪码.溯源码,帮助您更好的管理商品防伪码. 魔众一物一码溯源防伪系统发布v1.2.0版本,新功能和Bug修复累计10项,增加二维码显示页面,后台升级. 20 ...
- java生成微信支付sign 及校验签名封装
需要工具类的可以联系博主~~ /*** 生成微信支付sign** @param params(可排序)* @param key* @return*/public static String creat ...
- [Flutter]微信分享并从分享链接跳回APP指定页面
最近在使用flutter开发APP,flutter实现了一套代码同时生成Android和iOS两个平台的APP,可以实现零基础快速上手APP开发,缩短开发周期.但flutter仍处于较快增长期,版本迭 ...
- java pdf水印排布问题_java实现图片和pdf添加铺满文字水印
依赖jar包 com.itextpdf itextpdf 5.3.2 com.itextpdf itext-asian 5.2.0 一,图片添加铺满水印 ======================= ...
最新文章
- C# 子窗口修改主窗口的控件
- Windows Phone 7用户界面原型截图汇总
- 兴业银行与第四范式开启AI平台加速模式 毫秒级信用卡反欺诈系统上线
- VTK:可视化算法之DataSetSurface
- NAT STURN,ICE
- AI实战分享 | 基于CANN的辅助驾驶应用案例
- 【目标定位】基于matlab扩展卡尔曼算法SLAM(运动轨迹+误差 )【含Matlab源码 1637期】
- python制作课程表_创建课程表设计
- Linux的SSH安装与配置OpenSSH
- endnote修改正文中参考文献标注_如何用endnote修改毕业论文后参考文献格式为毕业手册要求格式...
- 2019年9月中国编程语言排行榜
- verifier工具解决常见电脑故障
- 有趣的23000 同(近)意词
- mysql 重做日志_mysql redo log 重做日志
- 数据库中什么是内联接、左外联接、右外联接?
- 紫外线消毒器的催化反应工艺指南
- grabber的使用_Google Grabber —使用PHP找出您的域名在Google中列出了多少页
- VC驿站全套视频在线观看(B站)
- SQLite sqlite_master
- 解决url中times被转成×的问题
热门文章
- Mysql Field * doesn't have a default value解决方法
- 清华大学 zhongguo li 计算机,清华大学学者发表论文列表_郭美凤
- 罗技无线鼠标接收器无法配对的详细解决办法
- Android 系统广播(大全)
- Gitee使用流程及其注意事项
- MySQL生成随机数(正负值掺杂)
- 如何生成二维码?生成二维码其实很简单
- Python 股票分析入门
- lvs负载均衡之配置lvs-tun模式的httpd负载集群
- dismiss ios pop效果_iOS ~ ViewController的Push,Pop和Present,Dismiss转场动画