目录
前言
一些原创软件或网站的图片都会有自己的水印logo,上传时加入还是下载时加入都可,目的就是添加自己的水印版权。本次将图片添加水印+转出网络路径结合奉上。
介绍
java 生成图片水印的两种方式
1:利用jdk自带工具类实现图片添加 文字或则图片水印,不依赖第三方组件
2:可以通过thumbnailator库 实现水印添加
使用
创建图片加水印工具类 ImageWatermarkUtils
import org.apache.commons.lang3.StringUtils;
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.InputStream;
import java.io.OutputStream;
import java.util.Date;
import static com.ruoyi.common.utils.TencentUtils.picCOS;
/**
* 图片添加水印工具类
* 文字水印 图片水印 利用jdk ,不依赖第三方
*/
public class ImageWatermarkUtils {
// 水印透明度
private static float alpha = 0.3f;
// 水印横向位置
private static int positionWidth = 100;
// 水印纵向位置
private static int positionHeight = 100;
// 水印文字字体
private static Font font = new Font("宋体", Font.BOLD, 32);
// 水印文字颜色
private static Color color = Color.GRAY;
/**
* @param args
*/
public static void main(String[] args) {
//要加水印的原图片
String srcImgPath = "C:\\Users\\like\\Pictures\\1.png";
//方法一 添加图片水印的 水印图片
String iconPath = "C:\\Users\\like\\Desktop\\icon.png";
// 给图片添加水印
// markImageByIcon(iconPath, srcImgPath, null, null);
String logoText = "Code quotient";
/**给图片添加文字水印**/
markImageByText(logoText, srcImgPath, null, -15);
}
/**
* 给图片添加水印、可设置水印图片旋转角度
*
* @param iconPath 水印图片路径
* @param srcImgPath 源图片路径
* @param targerPath 目标图片路径
* @param degree 水印图片旋转角度
*/
public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath, Integer degree) {
OutputStream os = null;
try {
if (StringUtils.isBlank(targerPath)) {
targerPath = srcImgPath.substring(0, srcImgPath.lastIndexOf("."))+ srcImgPath.substring(srcImgPath.lastIndexOf("."));
}
// 此处接的是原图片地址 也可以直接接取file直接赋值
Image srcImg = ImageIO.read(new File(srcImgPath));
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), 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();
float alpha = 1f; // 透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
/**
* 以下一算水印图位置,右下角
*/
int width = srcImg.getWidth(null);
int height = srcImg.getHeight(null);
int iconWidth = img.getWidth(null);
int iconHeight = img.getHeight(null);
int x = width - iconWidth;
int y = height - iconHeight;
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
// 表示水印图片的位置
g.drawImage(img, x, 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();
}
}
}
/**
* 给图片添加水印文字、可设置水印文字的旋转角度
*
* @param logoText
* @param srcImgPath
* @param targerPath
* @param degree
*/
public static void markImageByText(String logoText, String srcImgPath, String targerPath, Integer degree) {
InputStream is = null;
OutputStream os = null;
try {
if (StringUtils.isBlank(targerPath)) {
//生成水印图片的地址
targerPath = "E:\\文件\\" + new Date().getTime() + srcImgPath.substring(srcImgPath.lastIndexOf("."));
}
// 1、源图片 此处接的是原图片地址 也可以直接接取file直接赋值
Image srcImg = ImageIO.read(new File(srcImgPath));
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
// 2、得到画笔对象
Graphics2D g = buffImg.createGraphics();
// 3、设置对线段的锯齿状边缘处理
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);
// 4、设置水印旋转
if (null != degree) {
g.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getHeight() / 2);
}
// 5、设置水印文字颜色
g.setColor(color);
// 6、设置水印文字Font
g.setFont(font);
// 7、设置水印文字透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
// 计算水印位置 注:这里很重要 控制水印的位置和展示的多少 可灵活调整 下面的 10 /15(数值越小越密 10控制上下的间距 15控制左右的间距)
for (int height = -buffImg.getWidth() / 2; height < 1.5 * buffImg.getHeight(); height = height + 10 * font.getSize()) {
for (int weight = -buffImg.getWidth() / 2; weight < 1.5 * buffImg.getHeight(); weight = weight + 15 * font.getSize()) {
g.drawString(logoText, weight, height);
}
}
// 9、释放资源
g.dispose();
// 10、生成图片
os = new FileOutputStream(targerPath);
ImageIO.write(buffImg, "JPG", os);
System.out.println("已完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
File file =new File(targerPath);
try {
picCOS(file);//此处是COS工具类上传 将新生成水印文件赋值上传获取网络地址
deleteFile(targerPath); //上传成功后删除本地文件
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 删除文件
*
* @param filePath 文件
* @return
*/
public static boolean deleteFile(String filePath)
{
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists())
{
file.delete();
flag = true;
}
return flag;
}
// public static void main(String[] args) {
// String srcImgPath = "C:\\Users\\like\\Pictures\\1.png";
// String iconPath = "C:\\Users\\like\\Pictures\\2.png";
// String targerPath = "C:\\Users\\like\\Pictures\\3.png";
// try {
// Thumbnails.of(new File(srcImgPath)).scale(1f)
// .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(iconPath)), 1f)
// .toFile(targerPath);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
COS 上传方法
附上官方SDK 上传对象 | 腾讯云 (tencentcloud.com)
public static String picCOS(File cosFile) throws Exception {
COSCredentials cred = new BasicCOSCredentials("accessKey","secretKey");
// 2 设置bucket的区域, COS地域的简称请参照
// https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
// 3 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
//指定要上传到的存储桶
String bucketName = "bucketName";
String name = cosFile.getName();
//生成路径里的文件夹路径
String key = "qianzhui/"+new Date().getTime() + name.substring(name.indexOf("."));
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 如下的文件使用该接口
// 大文件上传请参照 API 文档高级 API 上传
// 指定要上传到 COS 上的路径
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, cosFile);
cosClient.putObject(putObjectRequest);
cosClient.shutdown();
Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
System.out.println(url);
return url.toString();
}
//其中 accessKey,secretKey 皆可在百度云cos找到 根据实际开发情况填写其他相关参数
上述举的例子是拿本地图片绝对路径进行操作实际开发过程中改成file文件可能更加适用,开发过程中根据实际需求修改。当然根据这个图片+水印图片的方法也可稍做修改为画布成海报方法。背景图+文案+或多张图片 根据实际情况控制字体和位置可以得到一张海报。
水印效果图
附:一个人最稀缺的一个能力:深耕自己!