花不多说 ,上代码

简单文字水印

// path 为原图片地址, outPath则是输出新图片地址public static void addWatermark(String path, String outPathInteger,String remark)  {try {File srcImgFile = new File(path);Image srcImg = ImageIO.read(srcImgFile);int srcImgWidth = srcImg.getWidth(null);int srcImgHeight = srcImg.getHeight(null);BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g = bufImg.createGraphics();g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);g.setColor(Color.BLACK);g.setFont(new Font("宋体", Font.BOLD, 26));//设置水印的坐标int x = 20;int y = 40;g.drawString(remark, x, y);  //从坐标x,y开始添加水印g.dispose();// 输出图片FileOutputStream outImgStream = new FileOutputStream(outPathInteger);ImageIO.write(bufImg, "jpg", outImgStream);outImgStream.flush();outImgStream.close();}catch (Exception e){e.printStackTrace();}}

图片水印/文字水印


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;public class ImageWaterMark {//srcimg 原图片地址 ,outpath 输出新突破地址 ,详见main的使用方法public static void waterPress(String srcImgPath, String outImgPath,Color markContentColor, int fontSize, String waterMarkContent) {try {String[] waterMarkContents = waterMarkContent.split("\\|\\|");// 读取原图片信息File srcImgFile = new File(srcImgPath);Image srcImg = ImageIO.read(srcImgFile);int srcImgWidth = srcImg.getWidth(null);int srcImgHeight = srcImg.getHeight(null);// 加水印BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);// 得到画笔对象Graphics2D g = bufImg.createGraphics();// 设置起点g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);Font font = new Font("宋体", Font.PLAIN, fontSize);// 根据图片的背景设置水印颜色g.setColor(markContentColor);// 设置水印文字字体g.setFont(font);// 数组长度int contentLength = waterMarkContents.length;// 获取水印文字中最长的int maxLength = 0;for (int i = 0; i < contentLength; i++) {int fontlen = getWatermarkLength(waterMarkContents[i], g);if (maxLength < fontlen) {maxLength = fontlen;}}for (int j = 0; j < contentLength; j++) {waterMarkContent = waterMarkContents[j];int tempX = 10;int tempY = fontSize;// 单字符长度int tempCharLen = 0;// 单行字符总长度临时计算int tempLineLen = 0;StringBuffer sb = new StringBuffer();for (int i = 0; i < waterMarkContent.length(); i++) {char tempChar = waterMarkContent.charAt(i);tempCharLen = getCharLen(tempChar, g);tempLineLen += tempCharLen;if (tempLineLen >= srcImgWidth) {// 长度已经满一行,进行文字叠加g.drawString(sb.toString(), tempX, tempY);// 清空内容,重新追加sb.delete(0, sb.length());tempLineLen = 0;}// 追加字符sb.append(tempChar);}// 通过设置后两个输入参数给水印定位//左下角/* g.drawString(sb.toString(), 0, srcImgHeight - (contentLength - j - 1) * tempY);*///右下角g.drawString(sb.toString(), srcImgWidth - maxLength, srcImgHeight - (contentLength - j - 1) * tempY);}g.dispose();// 输出图片FileOutputStream outImgStream = new FileOutputStream(outImgPath);ImageIO.write(bufImg, "jpg", outImgStream);outImgStream.flush();outImgStream.close();} catch (Exception e) {e.printStackTrace();}}public static int getCharLen(char c, Graphics2D g) {return g.getFontMetrics(g.getFont()).charWidth(c);}/*** 获取水印文字总长度** @paramwaterMarkContent水印的文字* @paramg* @return水印文字总长度*/public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());}/*** 给图片添加水印* @param iconPath 水印图片路径* @param srcImgPath 源图片路径* @param targerPath 目标图片路径*/public static void markImageByIcon(String iconPath, String srcImgPath,String targerPath) {markImageByIcon(iconPath, srcImgPath, targerPath, null) ;}/*** 给图片添加水印、可设置水印图片旋转角度* @param iconPath 水印图片路径* @param srcImgPath 源图片路径* @param targerPath 目标图片路径* @param degree 水印图片旋转角度*/public static void markImageByIcon(String iconPath, String srcImgPath,String targerPath, Integer degree) {OutputStream os = null;try {Image srcImg = ImageIO.read(new File(srcImgPath));Integer srcImgWidth = srcImg.getWidth(null);Integer srcImgHeight = srcImg.getHeight(null);System.out.println("srcImgWidth:"+srcImgWidth);System.out.println("srcImgHeight:"+srcImgHeight);BufferedImage buffImg = new BufferedImage(srcImgWidth,srcImgHeight, BufferedImage.TYPE_INT_RGB);// 得到画笔对象// Graphics g= buffImg.getGraphics();Graphics2D g = buffImg.createGraphics();// 设置对线段的锯齿状边缘处理g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);if (null != degree) {// 设置水印旋转g.rotate(Math.toRadians(degree),(double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);}// 水印图象的路径 水印一般为gif或者png的,这样可设置透明度ImageIcon imgIcon = new ImageIcon(iconPath);// 得到Image对象。Image img = imgIcon.getImage();//缩放水印图片 默认宽高20img.getScaledInstance(20,20,Image.SCALE_DEFAULT);float alpha = 1; // 透明度g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));// 表示水印图片的位置//计算中心的图片位置//原图-图片 /2Integer icon_x =( srcImgWidth -img.getWidth(null) ) /2 ;Integer icon_y =( srcImgHeight -img.getHeight(null) ) /2;icon_x  = icon_x > 0 ? icon_x : 0;icon_y = icon_y >0?icon_y :0;g.drawImage(img, icon_x, icon_y, null);g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));g.dispose();os = new FileOutputStream(targerPath);// 生成图片ImageIO.write(buffImg, "JPG", os);} catch (Exception e) {e.printStackTrace();} finally {try {if (null != os)os.close();} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) {/*  // 原图位置, 输出图片位置, 水印文字颜色, 水印文字String font = "这里是文字水印哟  \n 2022-07-22 00:00:00";String img1= "D:/tmp/1.png";//原地址String img2 = "D:/tmp/2.jpg";//新地址Color color = Color.black;waterPress(img1, img2, color, 16, font);*/String srcImgPath = "D:/tmp/1.png";String iconPath = "D:/tmp/icon.png";String targerPath = "D:/tmp/3.jpg" ;// 给图片添加水印markImageByIcon(iconPath, srcImgPath, targerPath );}
}

图片转pdf

这里需要引入jar包
pom.xml

<dependency><groupId>com.lowagie</groupId><artifactId>itext</artifactId><version>2.1.7</version></dependency>
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.util.CollectionUtils;import java.io.*;
import java.util.ArrayList;
import java.util.List;public class Img2PdfUtil {public static void main(String[] args) {/* List<String> source = new ArrayList<String>();//替换为你们自己的图片地址source.add("https://baidu.com/img/A/YMXXXX946-2494_YM0000.jpg");source.add("https://baidu.com/img/A/YMXXXX946-2494_YM0000.jpg");ImgChangePDF(source, "D:/tem/PDF/test.pdf");*/try {List<String> source = new ArrayList<String>();source.add("D:/tmp/1.png");imageToPdf(source,"D:/tmp/test.pdf");} catch (Exception e) {e.printStackTrace();}}/*** 图片转pdf* @param images* @param outFileName* @throws Exception*/public static void imageToPdf(List<String> images, String outFileName) throws Exception {OutputStream out = new FileOutputStream(new File(outFileName));Document document = new Document();// 设置文档页边距document.setMargins(0, 0, 0, 0);try {PdfWriter.getInstance(document, out);// 打开文档document.open();if(!CollectionUtils.isEmpty(images)){for (String url:images) {try {Image image = getImage(url);// 设置页面宽高与图片一致Rectangle rectangle = new Rectangle(image.getScaledWidth(), image.getScaledHeight());document.setPageSize(rectangle);// 新建一页添加图片document.newPage();document.add(image);} catch (Exception e) {e.printStackTrace();}}}} finally {// 关闭文档document.close();try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}}/*** 获取图片* @param url* @return* @throws BadElementException* @throws IOException*/private static Image getImage(String url) throws BadElementException, IOException {// 获取图片的宽高Image image = Image.getInstance(url);// 调整图片缩放image.scaleToFit(600,600);// 图片居中image.setAlignment(Image.ALIGN_CENTER);return image;}}

文字生成图片

import sun.font.FontDesignMetrics;import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;import javax.imageio.ImageIO;/*** 如果一行文字长度超过了既定的宽度,那么主动执行换行操作*/
public class TextToImage {/*** 图片宽度*/private static int width = 960;/*** 每一行的高度*/private static int line_height = 24;/*** 字体*/private static Font font = new Font("宋体", Font.PLAIN, 14);public static void main(String[] args) throws Exception {String message = "这里输入你的文本,或者从文件系统中去读";String[] strArr = message.split("\n");createImage(strArr);}public static void createImage(String[] strArr) throws Exception {FontMetrics fm = FontDesignMetrics.getMetrics(font);int stringWidth = fm.charWidth('字');// 标点符号也算一个字//计算每行多少字 = 宽/每个字占用的宽度int line_string_num = width % stringWidth == 0 ? (width / stringWidth) : (width / stringWidth) + 1;System.out.println("每行字数=" + line_string_num);//将数组转为listList<String> strList = new ArrayList<>(Arrays.asList(strArr));//按照每行多少个字进行分割for (int j = 0; j < strList.size(); j++) {//当字数超过限制,就进行分割if (strList.get(j).length() > line_string_num) {//将多的那一端放入本行下一行,等待下一个循环处理strList.add(j + 1, strList.get(j).substring(line_string_num));//更新本行的内容strList.set(j, strList.get(j).substring(0, line_string_num));}}//计算图片的高度,多预留一行int image_height = strList.size() * line_height + line_height;//每张图片有多少行文字int every_line = image_height / line_height;for (int m = 0; m < 1; m++) {String filePath = "E:\\新建文件夹\\" + m + ".jpg";File outFile = new File(filePath);// 创建图片  宽度多预留一点BufferedImage image = new BufferedImage(width + 20, image_height,BufferedImage.TYPE_INT_BGR);Graphics g = image.getGraphics();g.setClip(0, 0, width + 20, image_height);g.setColor(Color.white); // 背景色白色g.fillRect(0, 0, width + 20, image_height);g.setColor(Color.black);//  字体颜色黑色g.setFont(font);// 设置画笔字体// 每张多少行,当到最后一张时判断是否填充满for (int i = 0; i < every_line; i++) {int index = i + m * every_line;if (strList.size() - 1 >= index) {
//                    System.out.println("每行实际=" + newList.get(index).length());g.drawString(strList.get(index), 0, line_height * (i + 1));}}g.dispose();ImageIO.write(image, "jpg", outFile);// 输出png图片}}}

文字+背景图生成图片

public int drawStringWithFontStyleLineFeed(Graphics g, String strContent, int locX, int locY, Font font, int rowWidth){g.setColor(Color.BLACK);//获取字符串 字符的总宽度int strWidth = getStringLength(g, strContent);System.out.println("每行字符宽度:" + rowWidth);//获取字符高度int strHeight = getStringHeight(g);//字符串总个数System.out.println("字符串总个数:" + strContent.length());if (strWidth > rowWidth) {int rowstrnum = getRowStrNum(strContent.length(), rowWidth, strWidth);int rows = getRows(strWidth, rowWidth);String temp = "";for (int i = 0; i < rows; i++) {//获取各行的Stringif (i == rows - 1) {//最后一行temp = strContent.substring(i * rowstrnum);} else {temp = strContent.substring(i * rowstrnum, i * rowstrnum + rowstrnum);}if (i > 0) {//第一行不需要增加字符高度,以后的每一行在换行的时候都需要增加字符高度locY = locY + strHeight;}g.drawString(temp, locX, locY);}} else {//直接绘制g.drawString(strContent, locX, locY);}return locY;}private int getRows(int strWidth,int rowWidth){int rows = 0;if (strWidth % rowWidth > 0) {rows = strWidth / rowWidth + 1;} else {rows = strWidth / rowWidth;}System.out.println("行数:" + rows);return rows;}private int  getStringHeight(Graphics g) {int height = g.getFontMetrics().getHeight();System.out.println("字符高度:"+height);return height;}private int getRowStrNum(int strnum, int rowWidth, int strWidth){int rowstrnum = 0;rowstrnum = (rowWidth * strnum) / strWidth;System.out.println("每行的字符数:" + rowstrnum);return rowstrnum;}private int  getStringLength(Graphics g,String str) {int strWidth = g.getFontMetrics().stringWidth(str);System.out.println("字符总宽度:"+strWidth);return strWidth;}//创建图片public static void createImage(String str, Font font, File outFile,File bgFile) throws Exception {BufferedImage bgImage =  ImageIO.read(bgFile);Integer width = bgImage.getWidth();Integer height = bgImage.getHeight();// 创建图片BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);Graphics2D g = image.createGraphics();g.setClip(0, 0, width, height);g.setColor(Color.WHITE);g.fillRect(0, 0, width, height);g.setFont(font);MyDrawText drawText = new MyDrawText();BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(str.getBytes()), Charset.forName("utf8")));String line;int locY = g.getFontMetrics().getHeight();while (null != (line = br.readLine())) {g.setColor(Color.BLACK);locY = drawText.drawStringWithFontStyleLineFeed(g, line, 0, locY, font, width - g.getFontMetrics().charWidth(' '));locY += g.getFontMetrics().getHeight();}g.dispose();// 输出png图片ImageIO.write(image, "jpg", outFile);}public static void main(String[] args) throws Exception {Font font = new Font("黑体", Font.BOLD, 16);String textTempImage = "C:/tmp/1.jpg";String sourceTempImage = "C:/tmp/2.jpg";createImage("你好啊",font,textTempImage ,sourceTempImage);}

上传图片到本地

  /**** @param imgUrl  上传图片地址* @param tempPath  临时存放路径 D:/aa/img04.jpg* @return*/public static void uploadImage(String imgUrl,String tempPath){// TODO Auto-generated method stubtry {//图片的http全路径URL url = new URL(imgUrl);BufferedInputStream  in = new BufferedInputStream(url.openStream());//保存的图片文件名File img = new File(tempPath);BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(img));byte[] buf = new byte[1];int len;while((len = in.read(buf)) != -1) {out.write(buf ,0,len);}in.close();out.close();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

java操作图片集合(添加图片水印、文字水印,文字生成图片,图片转pdf等)相关推荐

  1. java操作word,添加页眉,页眉图片,替换书签,添加水印(全)

    java操作word文档,添加页眉文本,页眉图片,替换书签,水印 原模板截图: 生成后的文档效果截图: 第一步:引入maven <dependency><groupId>spi ...

  2. Java操作Cookie之添加Cookie

    首先给大家分享一个巨牛巨牛的人工智能教程,是我无意中发现的.教程不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵段子,像看小说一样,哈哈-我正在学习中,觉得太牛了,所以分享给大家!点这里可以跳转 ...

  3. XE中FMX操作ListBox,添加上千条记录(含图片)

    我之前是想在ListBox的每个Item上添加一个图片,Item上所有的内容都是放在Object里赋值,结果发现加载一百条记录耗时四五秒: procedure TMainForm.AddItem; v ...

  4. java图片批量添加_java实现邮件中插入批量图片

    首先是MimeMessage这个类,继承于javax.mail.Message,底下还有IMAPMessage.POP3Message.SmartMimeMessage.SMTPMessage等实现, ...

  5. 图片添加二维码水印教程

    本博客介绍一下用jdk awt实现图片加文字水印和图片水印的方法 一.图片文字水印 import java.awt.AlphaComposite; import java.awt.Color; imp ...

  6. 如何将已有图片做成透明水印_如何批量给图片添加属于自己的全屏透明水印?其实方法很简单...

    原标题:如何批量给图片添加属于自己的全屏透明水印?其实方法很简单 今天我们来分享一个给图片批量添加全屏透明水印的小技巧,为什么要给图片添加全屏透明水印呢?就好比如说,我是做美食的,配图时候,做出来的劳 ...

  7. 不懂如何在图片上添加贴纸?马上教你图片加贴纸方法

    有时候我们拍摄的图片上,画面上偶尔会出现一些一些隐私的东西,这个时候怎么办呢?或许很多人首先会想到的就是马赛克吧,其实呢,马赛克确实能帮助我们遮挡住一些私密的东西,但是与此同时,它一方面影响美观,另一 ...

  8. jedis操作set_redis命令行操作set集合和java方式操作set集合

    sadd key member [member ...] 向集合中增加元素 SMEMBERS key 查询集合中所有的元素 srem key member [member ...] 移除集合中指定元素 ...

  9. Java实现在图片上添加文字(水印)

    今天分享一个:通过Java代码,给图片添加文字. 比如下面这个图片,我们在左下角就添加了一个文字版的水印,那么这是如何实现的呢 ? 目录 [1]获取原图片对象 (1.1)读取本地图片 (1.2)读取网 ...

最新文章

  1. python编程思维培养_Python教学:编程如何培养学生计算思维-最新教育资料
  2. ACL 2019开源论文 | 句对匹配任务中的样本选择偏差与去偏方法
  3. 第三讲:Asp.Net+Autofac+EF/ADO.NET Winform OA(3)-启用DevExpress皮肤功能
  4. VS2015配置freegult
  5. 搭建nginx流媒体服务器(支持HLS)
  6. java开源服务框架_Java框架服务
  7. 保护导师,从我做起;爱护博导,人人有责
  8. 深入理解Java 容器
  9. java.util.ArrayList
  10. 系统学习NLP(二十九)--BERT
  11. create-react-app 创建react应用环境变量(env)配置
  12. 打开Excle出现配置进度解决方法
  13. EPLAN电气设计实例入门教程pdf
  14. UiAutomator2—By、BySelector
  15. HCIE 数通资料下载 肖哥视频下载
  16. c/C++笔试题总结
  17. 基于Transformer的NLP智能对话机器人实战课程(第十六章、第十七章、第十八章)
  18. oracle设置事务隔离级别为读已提交,oracle的事务隔离级别和读一致性
  19. 最小生成树 | Prim算法 Kruskal算法 |C语言
  20. JAVA中XML读写

热门文章

  1. PTA数据结构练习题——旅游规划
  2. 基于ueditor 扩展的电子病历编辑器-新UI
  3. Cloudera系列(2)使用数据帧(DataFrame)和模式(Schemas)
  4. 西安电子科技大学硕士论文latex模板第1章修改为第一章
  5. Excel 2007 制作双Y轴图形
  6. 机器中的上帝-人工智能,冠状病毒,种族主义和宗教
  7. 基于android的防抖音直播,uniapp 仿火山 / 抖音短视频|uni-App+vue 直播实例
  8. 软件 2.0 时代的程序分析
  9. 多省市成立大数据局,加快大数据产业发展
  10. 不用手机,如何让猫给你打视频电话 | 日常小技