package weaver.gy.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
* 添加文字水印
*
* @author Yuk
*
*/
public class WaterMarkUtil {
/**
* 添加文字水印
*
* @param targetImg
* 目标图片路径,如:C://myPictrue//1.jpg
* @param pressText
* 水印文字, 如:中国证券网
* @param fontName
* 字体名称, 如:宋体
* @param fontStyle
* 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
* @param fontSize
* 字体大小,单位为像素
* @param color
* 字体颜色
* @param x
* 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y
* 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha
* 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public static void pressText(String targetImg, String pressText,
String fontName, int fontStyle, int fontSize, Color color, int x,
int y, float alpha) {
try {
File file = new File(targetImg);
// 读取图片流
BufferedImage img = ImageIO.read(file);
int imgWidth = img.getWidth();
if(imgWidth>1000 && imgWidth<2000){
fontSize = 20;
}else if(imgWidth > 2000){
fontSize = 30;
}else if(imgWidth<1000){
fontSize = 10;
}
if(pressText.equals("重打")){
y = fontSize;
}
BufferedImage image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
// 设置水印文字Font
g.setFont(new Font(fontName, fontStyle, fontSize));
// 设置水印文字颜色
g.setColor(color);
// 设置水印文字透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
int width_1 = fontSize * getLength(pressText);
int height_1 = fontSize;
int widthDiff = width - width_1;
int heightDiff = height - height_1;
if (x < 0) {
x = widthDiff / 2;
} else if (x > widthDiff) {
x = widthDiff;
}
if (y < 0) {
y = heightDiff / 2;
} else if (y > heightDiff) {
y = heightDiff;
}
// 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
g.drawString(pressText, x, y + height_1);
// 释放资源
g.dispose();
ImageIO.write(bufferedImage, "png", file);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
*
* @param text
* @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
*/
public static int getLength(String text) {
int textLength = text.length();
int length = textLength;
for (int i = 0; i < textLength; i++) {
if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
length++;
}
}
return (length % 2 == 0) ? length / 2 : length / 2 + 1;
}
public static void main(String[] args) {
pressText("D:/Demo/ceshi/a.tif", "武汉泛微", "宋体", 0, 100, new Color(
255, 0, 0), 100, 200, 0.8f);
}
}
图片添加文字水印
最新推荐文章于 2022-09-13 10:08:28 发布