package com.yx.zzg.image;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* @author zzg
*
*/
public class ImageUtil {
/**
* 文字水印
*
* @param pressText
* 水印文字
* @param targetImg
* 目标图片
* @param pressTextImg
* 水印后的图片
* @param fontName
* 字体名称
* @param fontStyle
* 字体样式
* @param color
* 字体颜色
* @param fontSize
* 字体大小
* @param x
* 修正值
* @param y
* 修正值
* @param alpha
* 透明度
*/
public static void pressText(String pressText, String targetImg,
String pressTextImg, String fontName, int fontStyle, Color color,
int fontSize, int x, int y, float alpha) {
try {
File targetFile = new File(targetImg);
File pressTextFile = new File(pressTextImg);
BufferedImage image = ImageIO.read(targetFile);
int width = image.getWidth(null);
int height = image.getHeight(null);
Graphics2D g = image.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.setColor(color);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
g.drawString(pressText, (width - (getLength(pressText) * fontSize))
/ 2 + x, (height - fontSize) / 2 + y);
g.dispose();
ImageIO.write(image, pressTextImg.substring(pressTextImg
.lastIndexOf(".") + 1, pressTextImg.length()),
pressTextFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
pressText("让图片打上文字", "C:\\Users\\toshiba\\DSCN0787.JPG",
"C:\\Users\\toshiba\\bb.jpg", "黑体", 400, Color.RED, 100, 90,
90, 0.3f);
}
public static int getLength(String text) {
int length = 0;
for (int i = 0; i < text.length(); i++) {
if (new String(text.charAt(i) + "").getBytes().length > 1) {
length += 2;
} else {
length += 1;
}
}
return length / 2;
}
}
图片上打上文字水印
最新推荐文章于 2024-07-09 13:22:42 发布