由于网上加水印需要RMB……,在别人的小轮子上面又改了改:
package club.housy.watermark.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
public class ImageUtil {
public void mark(BufferedImage bufImg, Image img, String text, Font font, Color color, int x, int y) {
RenderingHints rh=new RenderingHints(RenderingHints. KEY_ANTIALIASING,
RenderingHints. VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_STROKE_CONTROL
, RenderingHints.VALUE_STROKE_PURE);
rh.put(RenderingHints.KEY_ALPHA_INTERPOLATION
, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
Graphics2D g = bufImg.createGraphics();
g.setRenderingHints(rh);
g.drawImage(img, 0, 0, bufImg.getWidth(), bufImg.getHeight(), null);
g.setColor(color);
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g.rotate(Math.toRadians(15), (double) bufImg.getWidth() / 2,
(double) bufImg.getHeight() / 2);
g.drawString(text, x, y);
g.dispose();
}
public void mark(String imgPath, String outImgPath, String text, Font font, Color color, int x, int y) {
try {
// 读取原图片信息
File imgFile = null;
Image img = null;
if (imgPath != null) {
imgFile = new File(imgPath);
}
if (imgFile != null && imgFile.exists() && imgFile.isFile() && imgFile.canRead()) {
img = ImageIO.read(imgFile);
}
int imgWidth = img.getWidth(null);
int imgHeight = img.getHeight(null);
// 加水印
BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
mark(bufImg, img, text, font, color, x, y);
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(outImgPath);
ImageIO.write(bufImg, "jpg", outImgStream);
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Font font = new Font("微软雅黑", Font.BOLD, 24);
// for(int i = 1; i <= 33; i ++)
// new ImageUtil().mark("D:/Pictures/linux/sy1/sy1 (" + i + ").png", "D:/Pictures/linux/sy1/watermark/sy1 (" + i + ").png", "XXXX", font, Color.ORANGE, 350, 150);
for(int i = 1; i <= 23; i ++)
new ImageUtil().mark("D:/Pictures/linux/sy2/sy2 (" + i + ").png",
"D:/Pictures/linux/sy2/watermark/sy2 (" + i + ").png",
"XXX", font, Color.ORANGE, 100, 80);
}
}