File sourceImageFile = new File(“ C:\ Users \ Documents \ NetBeansProjects \ MyProject \ src \ asian \ paints \ images \ stations.png”); BufferedImage sourceImage = ImageIO.read(sourceImageFile);
File watermarkImageFile = new File("C:\\Users\\Documents\\NetBeansProjects\\MyProject\\src\\asian\\paints\\images\\error_indicate.png");
BufferedImage watermarkImage = ImageIO.read(watermarkImageFile);
File destImageFile = new File("C:\\Users\\Desktop\\watermarked.png");
// initializes necessary graphic properties
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
g2d.setComposite(alphaChannel);
new Timer(0, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try {
Jedis jedis = new Jedis("localhost");
// calculates the coordinate where the image is painted
int topLeftX = Integer.parseInt(jedis.get("x")) ;
int topLeftY = Integer.parseInt(jedis.get("y")) ;
System.out.println("x " + topLeftX);
System.out.println("y " + topLeftY);
// paints the image watermark
g2d.drawImage(watermarkImage, topLeftX, topLeftY, null);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
// System.out.println(“图像水印已添加到图像中。”);
ImageIcon iconLogo = new ImageIcon("C:\\Users\\Desktop\\watermarked.png");
// In init() method write this code
jLabel1.setIcon(iconLogo);
} catch (IOException ex) {
System.err.println(ex);
}
}
}).start();
以上程序仅在执行时第一次更改水印位置。此后它将不会更改其位置。