以下代码只供参考,角度会根据内容的大小不一定是正好对角,需要对x,y的值进行微调。
效果如下:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.math.BigDecimal;
public class Watermark3 {
private final static String RIGHT="RIGHT";
private final static String LEFT="LEFT";
private final static String PX="PX";
private final static double precision =1.2;
public static void main(String[] args) throws IOException {
createImg(RIGHT);
createImg(PX);
createImg(LEFT);
}
public static void createImg(String param) throws IOException {
int fontSize = 20;
String str = "我是水印";
int textLength = getTextLength(str);
BigDecimal width = getWidth(textLength, fontSize, param);
BigDecimal height = getHeight(textLength, fontSize, param);
BufferedImage bi = new BufferedImage(width.intValue(), height.intValue(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setBackground(Color.WHITE);
g.clearRect(0, 0, width.intValue(), height.intValue());
g.setFont(new Font("宋体", Font.ITALIC, fontSize));
g.setColor(Color.LIGHT_GRAY);
// g.rotate(-30 * Math.PI / 180);//倾斜30度
if(RIGHT.equals(param)){
g.rotate(Math.toRadians(-45),0,height.doubleValue()+10);//设置水印旋转
g.drawString("我是水印", 15, height.intValue()+10);
}
if(LEFT.equals(param)){
g.rotate(Math.toRadians(45),0,0);//设置水印旋转
g.drawString("我是水印", 5, 5);
}
if(PX.equals(param)){
g.drawString("我是水印", 0, 20);
}
g.dispose();
bi.flush();
ImageIO.write(bi, "png", new File("/Users/temp_dir/temp1/c/test-"+param+".png"));
}
private static BigDecimal getWidth(int textLength,int fontSize, String str){
if(PX.equals(str)){
return new BigDecimal(textLength *fontSize).setScale(0,BigDecimal.ROUND_HALF_UP);
}
if(RIGHT.equals(str)){
BigDecimal width = new BigDecimal( precision*textLength * fontSize*Math.cos(Math.toRadians(45))).setScale(0, BigDecimal.ROUND_HALF_UP);
return width;
}
if(LEFT.equals(str)){
return new BigDecimal(precision*textLength *fontSize* Math.cos(Math.toRadians(-45))).setScale(0,BigDecimal.ROUND_HALF_UP);
}
return BigDecimal.ZERO;
}
private static BigDecimal getHeight(int textLength,int fontSize, String str){
if(PX.equals(str)){
return new BigDecimal(fontSize);
}
if(RIGHT.equals(str)){
BigDecimal height = new BigDecimal(precision*textLength *fontSize* Math.sin(Math.toRadians(45))).setScale(0,BigDecimal.ROUND_HALF_UP);
return height;
}
if(LEFT.equals(str)){
return new BigDecimal(precision*textLength *fontSize* Math.cos(Math.toRadians(-45))).setScale(0,BigDecimal.ROUND_HALF_UP);
}
return BigDecimal.ZERO;
}
private static int getTextLength (String text) {
int length = text.length ();
for (int i = 0; i < text.length (); i++) {
String s = String.valueOf (text.charAt (i));
if (s.getBytes ().length > 1) {
length++;
}
}
length = length % 2 == 0 ? length / 2 : length / 2 + 1;
return length;
}
}