根据图片实际宽高自适应调整字号、水印绘制的坐标
package util;
import java.io.* ;
import java.text.DecimalFormat;
import com.sun.image.codec.jpeg.* ;
import java.awt.* ;
import java.awt.image.BufferedImage;
import java.awt.image.* ;
import javax.imageio.ImageIO;
import javax.swing.* ;
import javax.swing.filechooser.FileSystemView;
public class Shuiyin {
public static void main(String[]args) throws Exception{
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath();
boolean flag = createMark("你的原图路径", "自定义水印", Color.GRAY, 0.5f);
System.out.println(flag);
}
/**
* @param filePath 原图路径
* @param markContent 文字水印内容
* @param markContentColor 文字水印颜色
* @param alpha 文字水印透明度
* @return
*/
public static boolean createMark(String filePath, String markContent, Color markContentColor, float alpha) {
DecimalFormat df=new DecimalFormat("0.00"); //避免除法仅保留整数
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath(); //获取桌面路径
ImageIcon imgIcon = new ImageIcon(filePath);
Image theImg = imgIcon.getImage();
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
System.out.println(width + " " + height);
BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
g.setColor(markContentColor);
g.setBackground(Color.white);
Font f = new Font("黑体", Font.ITALIC, (int) Double.parseDouble(df.format((float)width/5000*240)));
g.setFont(f);
g.drawImage(theImg, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
for (int i = 1; i < 8; i++) {
if(i%2 != 0) {
g.drawString(markContent, (int)(width / 8 * 0.6), i * height / 8); // 添加水印的文字和设置水印文字出现的内容
} else if(i%2 == 0) {
g.drawString(markContent, (int)(width / 8 * 2), i * height / 8); // 添加水印的文字和设置水印文字出现的内容
}
}
g.dispose();
try {
FileOutputStream out = new FileOutputStream("你的输出路径");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
// param.setQuality(qualNum, true);
encoder.encode(bimage, param);
out.close();
} catch (Exception e) {
return false;
}
return true;
}
}