版权声明 :

本文为博主原创文章,如需转载,请注明出处(https://blog.csdn.net/F1004145107/article/details/84317601)

本文包含俩部分,使用的是 java.awt.Graphics2D 

1.生成二维码(彩色二维码,去白边)

2.将二维码、文字合成到图片上面

          代码的逻辑都在注释里面了,如果有不懂的可以私信我,代码中的图片可以做测试,链接均可用

    public static void main(String[] args) {java.awt.Font font = new java.awt.Font("宋体", java.awt.Font.BOLD, 36);// 添加字体的属性设置InputStream is = null;try {// 图片1BufferedImage backImg = ImageIO.read(new URL("http://wisezhe.oss-cn-beijing.aliyuncs.com/18-11-21/87298612.jpg"));// 图片2String urlStr = "http://wisezhe.oss-cn-beijing.aliyuncs.com/18-11-21/59672258.jpg";URL url = new URL(urlStr);// 打开连接URLConnection con = url.openConnection();// 设置请求超时为5scon.setConnectTimeout(5 * 1000);// 输入流is = con.getInputStream();BufferedImage imageLocal = ImageIO.read(is);// 加载用户的二维码BufferedImage imageCode = ImageIO.read(new URL(getQrCode()));// 创建模板Graphics2D g = imageLocal.createGraphics();g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 在模板上添加用户二维码(地址,左边距,上边距,图片宽度,图片高度),值都为像素g.drawImage(imageCode, 474, 42, 170, 170, null);g.setFont(font);// 设置刷子颜色g.setColor(new java.awt.Color(148, 134, 118));// 添加文字g.drawString("我是wise", 60, 129);// 完成模板修改g.dispose();// 合成图片imageLocal = PictureUtils.mergeImage(backImg, imageLocal, false, 0, 0);// 将图片直接生成到桌面File file = new File("C:\\Users\\Administrator\\Desktop\\test.jpg");ImageIO.write(imageLocal, "jpg", file);// 如果图片需要返回使用下列代码即可,上传图片并且返回图片url
//            ByteArrayOutputStream outPutStream =3 new ByteArrayOutputStream();
//            ImageIO.write(imageLocal, "jpg", outPutStream);
//            String s = UploadUtils.submitImage(id + ".jpg", outPutStream.toByteArray());
//            String key = "";
//            BaseUpImageEntity baseUpImageEntity = JacksonUtil.readValue(s, BaseUpImageEntity.class);
//            if (baseUpImageEntity != null && "0".equals(baseUpImageEntity.getHead().getRspStatusCode())) {
//                key = baseUpImageEntity.getBody().getUrl();
//            }} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 生成用户二维码** @author wise* @return java.lang.String*/private static String getQrCode() {// 跳转链接String content = "https://www.google.com/";ByteArrayOutputStream baos = null;String url = "";try {baos = new ByteArrayOutputStream();MultiFormatWriter multiFormatWriter = new MultiFormatWriter();Map hints = new HashMap();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);// 去掉二维码的白边bitMatrix = updateBit(bitMatrix, 0);// 生成彩色二维码BufferedImage bufferedImage = toBufferedImage(bitMatrix);ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "jpg", outPutStream);String json = UploadUtils.submitImage("xxxxxx.jpg", outPutStream.toByteArray());// 如不需生成彩色二维码直接使用下面被注释掉的代码即可
//          MatrixToImageWriter.writeToStream(bitMatrix, "jpg", baos);
//          String json = UploadUtils.submitImage(id + uid + ".jpg", baos.toByteArray());BaseUpImageEntity baseUpImageEntity = JacksonUtil.readValue(json, BaseUpImageEntity.class);if (baseUpImageEntity != null && "0".equals(baseUpImageEntity.getHead().getRspStatusCode())) {url = baseUpImageEntity.getBody().getUrl();}return url;} catch (Exception e) {e.printStackTrace();} finally {try {if (baos != null) {baos.close();}} catch (IOException e) {e.printStackTrace();}}return null;}/*** 去掉二维码的白边* * @author wise* @param matrix* @return com.google.zxing.common.BitMatrix*/public static BitMatrix updateBit(BitMatrix matrix, int margin) {int tempM = margin * 2;// 获取二维码图案的属性int[] rec = matrix.getEnclosingRectangle();int resWidth = rec[2] + tempM;int resHeight = rec[3] + tempM;// 按照自定义边框生成新的BitMatrixBitMatrix resMatrix = new BitMatrix(resWidth, resHeight);resMatrix.clear();// 循环,将二维码图案绘制到新的bitMatrix中for (int i = margin; i < resWidth - margin; i++) {for (int j = margin; j < resHeight - margin; j++) {if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {resMatrix.set(i, j);}}}return resMatrix;}/**  * 生成彩色二维码* * @author  wise* @param matrix* @return  java.awt.image.BufferedImage*/public static BufferedImage toBufferedImage(BitMatrix matrix) {// 背景颜色 RGB:242,241,236Integer backColor = 0xF2F1EC;//十六进制// 二维码颜色 RGB:148,134,118Integer qrCodeColor = 0x948676;//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) ? qrCodeColor : backColor);}}return image;}

俩张图片进行合成的工具类源码

package com.shengya.service.utils;import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;/*** @author wise*/
public class PictureUtils {/*** @param fileUrl 文件绝对路径或相对路径* @return 读取到的缓存图像* @throws IOException 路径错误或者不存在该文件时抛出IO异常*/public static BufferedImage getBufferedImage(String fileUrl) throws IOException {File f = new File(fileUrl);return ImageIO.read(f);}/*** @param savedImg 待保存的图像* @param saveDir  保存的目录* @param fileName 保存的文件名,必须带后缀,比如 "beauty.jpg"* @param format   文件格式:jpg、png或者bmp* @return*/public static boolean saveImage(BufferedImage savedImg, String saveDir, String fileName, String format) {boolean flag = false;// 先检查保存的图片格式是否正确String[] legalFormats = {"jpg", "JPG", "png", "PNG", "bmp", "BMP"};int i = 0;for (i = 0; i < legalFormats.length; i++) {if (format.equals(legalFormats[i])) {break;}}if (i == legalFormats.length) { // 图片格式不支持System.out.println("不是保存所支持的图片格式!");return false;}// 再检查文件后缀和保存的格式是否一致String postfix = fileName.substring(fileName.lastIndexOf('.') + 1);if (!postfix.equalsIgnoreCase(format)) {System.out.println("待保存文件后缀和保存的格式不一致!");return false;}String fileUrl = saveDir + fileName;File file = new File(fileUrl);try {flag = ImageIO.write(savedImg, format, file);} catch (IOException e) {e.printStackTrace();}return flag;}/*** 待合并的两张图必须满足这样的前提,如果水平方向合并,则高度必须相等;如果是垂直方向合并,宽度必须相等。* mergeImage方法不做判断,自己判断。** @param img1         待合并的第一张图* @param img2         带合并的第二张图* @param isHorizontal 为true时表示水平方向合并,为false时表示垂直方向合并* @return 返回合并后的BufferedImage对象* @throws IOException*/public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, boolean isHorizontal, int startX, int startY) throws IOException {int w1 = img1.getWidth();int h1 = img1.getHeight();int w2 = img2.getWidth();int h2 = img2.getHeight();// 从图片中读取RGBint[] ImageArrayOne = new int[w1 * h1];ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中int[] ImageArrayTwo = new int[w2 * h2];ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);// 生成新图片BufferedImage DestImage = null;if (isHorizontal) { // 水平方向合并DestImage = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGBDestImage.setRGB(startX, startY, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB} else { // 垂直方向合并DestImage = new BufferedImage(w1, h1 + h2, BufferedImage.TYPE_INT_RGB);DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGBDestImage.setRGB(0, h1, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB}return DestImage;}}

   在只用工具类时可能会报java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!异常,原因是俩张图片的尺寸问题,如果进行垂直合成就必须保证俩张图片的宽度像素是一样,水平合成需保证高度像素是一样

Java合成图片及文字--Graphics2D相关推荐

  1. JAVA合成图片和文字

    创建一张原始图片 BufferedImage img = new BufferedImage(533, 800, BufferedImage.TYPE_INT_RGB);//创建图片 1 Buffer ...

  2. java 给图片添加文字

    java 给图片添加文字 最近开发中要实现给图片加文字功能,本打算用Jmagick实现的,可是中文出现乱码,没有找到解决办法,就用 最原始的方法实现了,如果随知道Jmagick图片解决中文乱码问题,可 ...

  3. .net core Graphics合成图片加文字

    .net core Graphics合成图片加文字 引用: using System; using System.Drawing; using System.Drawing.Text; 代码 stat ...

  4. 用Java实现图片转文字的功能具体流程

    要实现图片转文字的功能,我们可以使用OCR(Optical Character Recognition,光学字符识别)技术.OCR技术可以将图片中的文字转换成计算机可识别的文本格式.在Java中,我们 ...

  5. 手把手教你如何通过Java给图片添加文字和图片水印

    本文首发于个人网站 前言 最近工作上有个需求,动态生成一张图片,具体来说就是基于模版图片动态添加文字和图片(文字内容不同,图片数目不同),其中文字大小不全一样,且对位置有所要求. 本文将剖析多个技术方 ...

  6. java制作海报工具类,java操作图片贴图,java给图片添加文字,调整字体颜色大小间距

    工具类 java操作图片,给一个大图片贴小图片,给图片添加文字并调整文字颜色,大小,字体间距,把本地图片或者网络图片加载到缓冲区 主要方法: imageIoRead方法,把图片加载到缓冲区 merge ...

  7. JAVA - base64图片加文字水印

    场景为:前端传入转码后的base64图片字符串,后台加水印并转为图片,再上传 使用postman调试接口时,总会出现400bad request的情况 若是把图片转码的base64编码放在header ...

  8. Java给图片添加文字,水印,文件或者http图片地址,可消除文字锯齿

    记一次Java给图片添加水印方法 Java给图片在指定位置加水印的小工具, 可操作文件, 或者http地址图片,转base64或者直接输出都可 核心代码先贴出来 水印基本信息的一个封装 import ...

  9. JAVA 给图片添加文字水印

    水印操作有很多,例如:给图片添加文字.图片水印,给pdf文件添加水印,给文件加盖公章,这类需求还是时常会遇到的,今天就简单记录一下给图片添加文字水印的demo,仅供大家参考,后续会写别的情况的添加水印 ...

  10. Java给图片添加文字水印

    闲着没事,研究了下图片水印的事儿,图片水印虽然恶心,而且大大的影响了图片的美观,试想一下,一张美女的性感写真照,下方来了个大大的水印"XXXX所有",看着那猥琐的文字水印,是不是很 ...

最新文章

  1. protoc-3.2.0-win32转java文件
  2. Linux Shell常用技巧(七)
  3. Spring IOC 容器源码分析 - 创建单例 bean 的过程
  4. WinHand.cpp Line 199 错误 WinHand.cpp Line 218 错误
  5. 不删除侦听器–使用ListenerHandles
  6. Android studio Mac 版  Plugin Error Plugin “GsonFormat4DataBinding“ is incompatible
  7. bzoj 4563 [Haoi2016]放棋子 错位排列+高精度
  8. 小学音乐教学和计算机的融合,【多媒体技术论文】小学音乐多媒体教学融入策略问题(共5881字)...
  9. ezcad旋转轴标刻参数_激光打标机软件ezcad中地球仪标刻使用方法教程详解
  10. ASA 5520 ASDM 配置
  11. we7 php 反编译,微擎人人商城小程序前端反编译解包还原教程
  12. 摸爬滚打半年,我是如何从小白进阶到渗透测试工程师
  13. XAMARIN运行IPHONE模拟器
  14. ajax聊天室创建群聊,js+node.js+socket.io实现聊天功能(私聊,创建群聊)
  15. 红黑树解决了什么问题
  16. 使用FFMPEG将WebM转为MP4或MKV
  17. 如何在远程工作中保持企业文化的凝聚力
  18. 1.01.21盒子模型,浮动,定位
  19. 伯努利分布(二项分布)的假设检验
  20. Win7停服,UOS如何应对?

热门文章

  1. Metro 风格应用的导航设计
  2. 跑跑卡丁车手游怎么用电脑玩 跑跑卡丁车模拟器玩法教程
  3. ASP.NET 安全认证(如何运用 Form 表单认证)(转帖)
  4. VMware Workstation安装windows xp系统并创建虚拟软盘
  5. JAVA关键字final修饰类,深入分析java中的关键字final
  6. 浅谈大数据的过去、现在和未来
  7. STM32 ME909 调试难点
  8. Spring IoC 容器的设计与实现原理
  9. kubernetes(K8s)容器设计模式实践案例 多节点选举模式
  10. UG基础知识学习视频目录整理(制图篇)