[英]Masking a BufferedImage
您将如何在特定部分上叠加两个BufferedImage
对象?
假设您有两个BufferedImage
对象,并且您有一个Rectangle2D
对象列表。 您想在矩形处用第二个BufferedImage
覆盖第一个BufferedImage
。 你会怎么做?
您使用TexturePaint
并绘制一个矩形!
首先,使用BufferedImage result = new BufferedImage(<width>,<height>,<colorMode>)
创建 output 图像,然后使用Graphics2D g = result.createGraphics()
创建并获取Graphics2D
object。
然后使用g.drawImage(<sourceImage>, null, 0, 0)
将完整的源图像 (Image1) 绘制到 output 图像上。
为了覆盖BufferedImage
,我们将使用TexturePaint
和g.fill(rect)
方法; 您想使用这样的 for 循环遍历所有矩形: for (Rectangle2D rect: rectangles)
在TexturePaint
的构造函数中,您使用BufferedImage.getSubImage(int x, y, width, height)
方法裁剪图像在矩形上获取所需的覆盖部分(Image2),然后在第二部分中使用Rectangle2D
来适应图像以确保它不会拉伸。 之后,您使用g.fill(rect)
将(纹理)矩形绘制到 output 图像上。
最后,您可以使用 output 映像做任何您想做的事情。 在以下示例中,我使用ImageIO
将其导出到.png
文件中。
例子:
图片1: https://i.stack.imgur.com/L0Z2k.jpg
图片2: https://i.stack.imgur.com/cmiAR.jpg
Output: 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:为此创建一个简单的访问方法,但由于我现在在手机上,所以我无法真正编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.