屏蔽BuffereImage

wyyhbhjk  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(361)

你要怎么做 BufferedImage 物体在特定的部位上互相重叠?
假设你有两个 BufferedImage 对象,并且您有一个 Rectangle2D 物体。要覆盖第一个 BufferedImage 与第二个 BufferedImage 在矩形上。你会怎么做?

ggazkfy8

ggazkfy81#

你用 TexturePaint 画一个长方形!
首先,使用 BufferedImage result = new BufferedImage(<width>,<height>,<colorMode>) ,然后创建并获取 Graphics2D 对象使用 Graphics2D g = result.createGraphics() .
然后使用将完整的源图像(image1)绘制到输出图像上 g.drawImage(<sourceImage>, null, 0, 0) .
覆盖 BufferedImage 我们将使用 TexturePaint 以及 g.fill(rect) 方法;要使用for循环遍历所有矩形,如下所示: for (Rectangle2D rect : rectangles)TexturePaint 你使用 BufferedImage.getSubImage(int x, y, width, height) 方法在矩形上裁剪图像以获得所需的覆盖部分(image2),然后在第二部分中使用 Rectangle2D 调整图像以确保它不会拉伸。之后你用 g.fill(rect) 将(带纹理的)矩形绘制到输出图像上。
最后,您可以对输出图像执行任何操作。在下面的示例中,我将其导出到 .png 文件使用 ImageIO .
例子:
图像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:为此创建一个简单的访问方法,但由于我现在在手机上,我真的无法编写代码。

相关问题