以前的代码,给个参考 private static void makeNormalWaterMarkImage(File imgFile, File waterFile) throws Exception { final BufferedImage sourceImage = ImageIO.read(imgFile); final BufferedImage waterImage = ImageIO.read(waterFile); final int sWidth = sourceImage.getWidth(); final int sHeight = sourceImage.getHeight(); final int wWidth = waterImage.getWidth(); final int wHeight = waterImage.getHeight(); final int space = 5;
//保存图片 final String fileName = imgFile.getName(); final int index = fileName.lastIndexOf("."); final String suffix = fileName.substring(index + 1).toUpperCase(); final FileOutputStream out = new FileOutputStream(imgFile); ImageIO.write(sourceImage, suffix, out); out.close(); sourceImage.flush(); waterImage.flush(); }
private static void makeNormalWaterMarkImage(File imgFile, File waterFile) throws Exception {
final BufferedImage sourceImage = ImageIO.read(imgFile);
final BufferedImage waterImage = ImageIO.read(waterFile);
final int sWidth = sourceImage.getWidth();
final int sHeight = sourceImage.getHeight();
final int wWidth = waterImage.getWidth();
final int wHeight = waterImage.getHeight();
final int space = 5;
int drawWidth = wWidth;
int drawHeight = wHeight;
int drawX = space;
int drawY = sHeight - wHeight - space;
//如果水印图片的高度比原始图片高的话就不加水印咯
if(wHeight > sHeight) {
return;
} else if(wWidth > sWidth) {
final double scale = (double)sWidth / (double)wWidth;
drawWidth = sWidth;
drawHeight = (int)((double)wHeight * scale);
drawX = 0;
drawY = sHeight - drawHeight;
}
final double angle = 15.0;
//反走样并且将质量设置成绘制的首选项
final Graphics2D g2d = sourceImage.createGraphics();
final RenderingHints qualityHints =
new RenderingHints(RenderingHints.KEY_ANTIALIASING
, RenderingHints.VALUE_ANTIALIAS_ON); qualityHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(qualityHints);
//旋转30度角
final AffineTransform rotate =
AffineTransform.getRotateInstance(-Math.PI * angle/180.0, drawX, drawY);
g2d.setTransform(rotate); //设置透明度
final AlphaComposite ac =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
g2d.setComposite(ac); g2d.drawImage(waterImage
, drawX
, drawY
, drawWidth
, drawHeight
, null);
g2d.dispose();
//保存图片
final String fileName = imgFile.getName();
final int index = fileName.lastIndexOf(".");
final String suffix = fileName.substring(index + 1).toUpperCase();
final FileOutputStream out = new FileOutputStream(imgFile);
ImageIO.write(sourceImage, suffix, out);
out.close();
sourceImage.flush();
waterImage.flush();
}