java实现图片剪裁和加水印代码实现
时间: 2023-08-26 15:04:49 浏览: 142
很高兴回答你的问题!以下是Java实现图片剪裁和加水印的代码示例:
图片剪裁:
```java
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageCropExample {
public static void main(String[] args) throws Exception {
File input = new File("input.jpg");
BufferedImage image = ImageIO.read(input);
// 定义剪裁区域
Rectangle rect = new Rectangle(10, 10, 100, 100);
BufferedImage cropped = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
File output = new File("output.jpg");
ImageIO.write(cropped, "jpg", output);
}
}
```
图片加水印:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageWatermarkExample {
public static void main(String[] args) throws Exception {
File input = new File("input.jpg");
BufferedImage image = ImageIO.read(input);
// 创建Graphics2D对象
Graphics2D g2d = image.createGraphics();
// 设置水印文字字体、颜色和透明度
g2d.setFont(new Font("Arial", Font.BOLD, 36));
g2d.setColor(Color.RED);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
// 创建AffineTransform对象,设置水印文字旋转角度
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(30), image.getWidth() / 2, image.getHeight() / 2);
g2d.setTransform(at);
// 绘制水印文字
g2d.drawString("Watermark", image.getWidth() / 2, image.getHeight() / 2);
// 释放Graphics2D对象
g2d.dispose();
File output = new File("output.jpg");
ImageIO.write(image, "jpg", output);
}
}
```
希望能帮到你,如果还有其他问题,请随时提出!
阅读全文