有一个问题,就是fontsize字体的大小设置,因为不同图片像素不同,所以不知道怎么根据像素来设置字体大小。
/**
* 给图片添加水印文字、可设置水印文字的旋转角度
* @param logoText
* @param srcImgPath
* @param targerPath
* @param degree
* @param fontsize
*/
public static boolean addImgWater(String logoText, String srcImgPath, String targerPath, Integer degree, int fontsize) {
InputStream is = null;
OutputStream os = null;
try {
String ext = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1);
BufferedImage srcImg = ImageIO.read(new File(srcImgPath));
int imgwidth = srcImg.getWidth(null);
int imgheight = srcImg.getHeight(null);
BufferedImage buffImg = new BufferedImage(imgwidth,imgheight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg, 0, 0, null);
if (null != degree) {
g.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getHeight() / 2);
}
g.setColor(Color.red);
Font font = new Font("宋体",Font.BOLD, fontsize);
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.2f));
int positionWidth = buffImg.getWidth()/5;
int positionHeight = buffImg.getHeight()/2;
g.drawString(logoText, positionWidth, positionHeight);
g.dispose();
os = new FileOutputStream(targerPath);
ImageIO.write(buffImg, ext, os);
System.out.println("图片完成添加水印文字");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}