How to use Java to implement the image watermark function of the CMS system
Abstract: Adding the image watermark function to the CMS system can effectively prevent images from being tampered with and stolen. This article will introduce how to use Java to implement the image watermark function of the CMS system and provide code examples.
Step 1: Load the image
First, you need to load the image that needs to be added Watermark pictures. You can use Java's ImageIO class to load images. The code is as follows:
File file = new File("image.jpg"); BufferedImage image = ImageIO.read(file);
Step 2: Create a Graphics object
To operate the image by creating a Graphics object, the code is as follows:
Graphics2D g2d = (Graphics2D) image.getGraphics();
Step 3: Add watermark
Before adding a watermark to the picture, you can first set the font, font size, transparency and other attributes. Then, use the corresponding method of the Graphics object to draw text or graphics on the image. The code is as follows:
Font font = new Font("Arial", Font.BOLD, 12); g2d.setFont(font); g2d.setColor(Color.RED); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g2d.drawString("Copyright", 10, 10);
Step 4: Save the image
After adding the watermark, you need to save the image to the disk. The code is as follows:
ImageIO.write(image, "jpg", new File("watermarked_image.jpg"));
Complete code example:
import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageWatermark { public static void main(String[] args) { try { // 加载图片 File file = new File("image.jpg"); BufferedImage image = ImageIO.read(file); // 创建Graphics对象 Graphics2D g2d = (Graphics2D) image.getGraphics(); // 添加水印 Font font = new Font("Arial", Font.BOLD, 12); g2d.setFont(font); g2d.setColor(Color.RED); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g2d.drawString("Copyright", 10, 10); // 保存图片 ImageIO.write(image, "jpg", new File("watermarked_image.jpg")); } catch (Exception e) { e.printStackTrace(); } } }
Reference link:
The above is the detailed content of How to use Java to implement the image watermark function of CMS system. For more information, please follow other related articles on the PHP Chinese website!