您使用TexturePaint 并绘制一个矩形!
首先使用BufferedImage result = new BufferedImage(<width>,<height>,<colorMode>) 创建输出图像,然后使用Graphics2D g = result.createGraphics() 创建并获取Graphics2D 对象。
然后您使用g.drawImage(<sourceImage>, null, 0, 0) 将完整的源图像 (Image1) 绘制到输出图像上。
要覆盖BufferedImage,我们将使用TexturePaint 和g.fill(rect) 方法;
您想使用这样的 for 循环遍历所有矩形:for (Rectangle2D rect : rectangles)
在TexturePaint 的构造函数中,您使用BufferedImage.getSubImage(int x, y, width, height) 方法在矩形上裁剪图像以获得所需的覆盖部分(Image2),然后在第二部分中使用Rectangle2D 来适应图像以确保它不会拉伸。
之后,您使用g.fill(rect) 将(带纹理的)矩形绘制到输出图像上。
最后,您可以对输出图像做任何您想做的事情。在以下示例中,我使用ImageIO 将其导出到.png 文件中。
示例:
图片1:https://i.stack.imgur.com/L0Z2k.jpg
图片2:https://i.stack.imgur.com/cmiAR.jpg
输出:https://i.stack.imgur.com/KgNM2.png
代码:
package test;
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;
public class ImageMasking {
// Define rectangles
public static Rectangle2D[] rectangles = new Rectangle[]{
new Rectangle(0, 0, 350, 50),
new Rectangle(0, 0, 50, 225),
new Rectangle(0, 175, 350, 50)
};
public static void main(String[] args) throws IOException {
// Load images
BufferedImage image1 = ImageIO.read(new File("image1.jpg"));
BufferedImage image2 = ImageIO.read(new File("image2.jpg"));
// Create output file
File out = new File("out.png");
if (!out.exists()) {
if (!out.createNewFile()) {
throw new IOException("createNewFile() returned false");
}
}
// Create output image
BufferedImage result = new BufferedImage(image1.getWidth(), image1.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = result.createGraphics();
// Draw image1 onto the result
g.drawImage(image1, null, 0, 0);
// Masking
for (Rectangle2D rect : rectangles){
// Extract x, y, width and height for easy access in the getSubImage method.
int x = (int) rect.getX();
int y = (int) rect.getY();
int width = (int) rect.getWidth();
int height = (int) rect.getHeight();
// Setup and draw the rectangle
TexturePaint paint = new TexturePaint(image2.getSubimage(x,y,width,height), rect);
g.setPaint(paint);
g.fill(rect);
}
// Export image
ImageIO.write(result, "PNG", out);
}
}
// 编辑 ToDo:为此创建一个简单的访问方法,但由于我现在在手机上,我无法真正编码。