我试图在我的网站上为图片添加水印。我想要它的工作方式是在下载或显示在其他网站上时显示水印。在我的网站上,我想在没有水印的情况下显示它。如果将水印放在上图片上,那将是非常棒的。例如,通过使用一些图片元数据或http标头,可以做到上面提到的吗?或者是不可能执行此操作,我应该通过在上传时添加页脚并将其隐藏来实现吗?
答案 0 :(得分:2)
您可以参考以下链接:
为图片添加文字水印
static void addTextWatermark(String text, File sourceImageFile, File destImageFile) {
try {
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
// initializes necessary graphic properties
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(alphaChannel);
g2d.setColor(Color.BLUE);
g2d.setFont(new Font("Arial", Font.BOLD, 64));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(text, g2d);
// calculates the coordinate where the String is painted
int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2;
int centerY = sourceImage.getHeight() / 2;
// paints the textual watermark
g2d.drawString(text, centerX, centerY);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
System.out.println("The tex watermark is added to the image.");
} catch (IOException ex) {
System.err.println(ex);
}
}
将图像水印添加到图像
static void addImageWatermark(File watermarkImageFile, File sourceImageFile, File destImageFile) {
try {
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
BufferedImage watermarkImage = ImageIO.read(watermarkImageFile);
// initializes necessary graphic properties
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
g2d.setComposite(alphaChannel);
// calculates the coordinate where the image is painted
int topLeftX = (sourceImage.getWidth() - watermarkImage.getWidth()) / 2;
int topLeftY = (sourceImage.getHeight() - watermarkImage.getHeight()) / 2;
// paints the image watermark
g2d.drawImage(watermarkImage, topLeftX, topLeftY, null);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
System.out.println("The image watermark is added to the image.");
} catch (IOException ex) {
System.err.println(ex);
}
}