花不多说 ,上代码
简单文字水印
// 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();
//缩放水印图片 默认宽高20
img.getScaledInstance(20,20,Image.SCALE_DEFAULT);
float alpha = 1; // 透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
// 表示水印图片的位置
//计算中心的图片位置
//原图-图片 /2
Integer 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);
//将数组转为list
List<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++) {
//获取各行的String
if (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 stub
try {
//图片的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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}