Java编辑图片,进行裁剪,旋转,缩放,添加文字,添加水印编辑
时间: 2023-09-06 10:11:30 浏览: 175
利用Thumbnailator轻松实现图片缩放、旋转与加水印
可以使用Java提供的图像处理库,比如Java Advanced Imaging (JAI)或者Java ImageIO来编辑图片内容。以下是一个使用Java ImageIO库进行图片编辑的示例代码,包括裁剪、旋转、缩放、添加文字和添加水印:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageEditor {
public static void main(String[] args) throws Exception {
// 读取原始图片
BufferedImage originalImage = ImageIO.read(new File("original.jpg"));
// 裁剪图片
int x = 100;
int y = 100;
int width = 300;
int height = 200;
BufferedImage croppedImage = originalImage.getSubimage(x, y, width, height);
// 旋转图片
double angle = Math.toRadians(45);
AffineTransform transform = new AffineTransform();
transform.rotate(angle, originalImage.getWidth()/2, originalImage.getHeight()/2);
BufferedImage rotatedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = rotatedImage.createGraphics();
g.setTransform(transform);
g.drawImage(originalImage, 0, 0, null);
// 缩放图片
double scale = 0.5;
int newWidth = (int)(originalImage.getWidth() * scale);
int newHeight = (int)(originalImage.getHeight() * scale);
BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
g = scaledImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
// 添加文字
g = originalImage.createGraphics();
Font font = new Font("Arial", Font.BOLD, 24);
g.setFont(font);
g.setColor(Color.RED);
g.drawString("Hello World!", 50, 50);
// 添加水印
BufferedImage watermarkImage = ImageIO.read(new File("watermark.png"));
int watermarkX = originalImage.getWidth() - watermarkImage.getWidth() - 10;
int watermarkY = originalImage.getHeight() - watermarkImage.getHeight() - 10;
g.drawImage(watermarkImage, watermarkX, watermarkY, null);
// 将编辑后的图片保存到文件
ImageIO.write(croppedImage, "jpg", new File("cropped.jpg"));
ImageIO.write(rotatedImage, "jpg", new File("rotated.jpg"));
ImageIO.write(scaledImage, "jpg", new File("scaled.jpg"));
ImageIO.write(originalImage, "jpg", new File("text.jpg"));
}
}
```
运行此代码后,将生成几个编辑后的图片文件。您可以根据需要进行修改和扩展,以执行其他图像编辑操作。
阅读全文