import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class ImageMask {
public static void main(String[] args) throws IOException {
// 定义输入和输出文件夹
String inputFolder = "F:/image/";
String outputFolder = "F:/image/i/";
File inputDir = new File(inputFolder);
// 遍历输入文件夹中所有的图片
for (File inputFile : inputDir.listFiles()) {
if (!inputFile.getName().endsWith(".png") && !inputFile.getName().endsWith(".jpg")) {
// 如果不是图片文件则跳过
continue;
}
// 读取图片
BufferedImage image = ImageIO.read(inputFile);
// // 定义随机遮罩矩形
Random random = new Random();
int x = random.nextInt(image.getWidth() / 2);
int y = random.nextInt(image.getHeight() / 2);
int width = random.nextInt(image.getWidth() / 2);
int height = random.nextInt(image.getHeight() / 2);
// 定义遮罩矩形
//todo:如果报错,改变里面的数值
Rectangle2D.Double rectangle1 = new Rectangle2D.Double(x, 10, width, 20);
Rectangle2D.Double rectangle2 = new Rectangle2D.Double(x, 80, 80, height);
// 将遮罩应用到原始图像上
BufferedImage masked = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = masked.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.setComposite(AlphaComposite.Clear);
g2d.fill(rectangle2);
g2d.setComposite(AlphaComposite.Src);
g2d.drawImage(image.getSubimage((int) rectangle2.getX(), (int) rectangle2.getY(),
(int) rectangle2.getWidth(), (int) rectangle2.getHeight()),
(int) rectangle1.getX(), (int) rectangle1.getY(),
null);
g2d.dispose();
// 保存处理后的图像到输出文件夹中
String outputFilePath = outputFolder + inputFile.getName();
File outputFile = new File(outputFilePath);
ImageIO.write(masked, "png", outputFile);
}
}
}
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.5.4</version>
</dependency>
</dependencies>