合并两个大小不同的图像,以使其正确重叠

时间:2018-11-02 09:00:35

标签: java java-2d

我有两张尺寸不同的图像。我要合并这两个图像,以便正面图像正确覆盖背景图像。

背景(宽度:144高度:147):enter image description here

前:(宽度:227高度:238)enter image description here

目前,我的结果看起来像这样,但是我需要它完美覆盖 enter image description here

我的方法是。 我正在将较小的图像调整为较大的图像。为此,我使用了一个名为imgscalr(https://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib/4.2)的外部库。 如您所见,结果图像不正确,因此我尝试缩放正面图像以使其覆盖背景,并且当我在背景上绘制正面图像时,我也更改了x / y的根,但仍然存在差异。知道如何合并两个图像,使笔触图像(正面)覆盖背景。

public static byte[] mergeBackgroundWithStrokes(byte[] backgroundImage, byte[] frontImage)
        throws IOException, PDProcessingException {

    Path backgroundfile = readAllBytes(backgroundImage, "background");
    Path outputFile = Files.createTempFile("output", ".png");

    BufferedImage backgroundBuffImg = ImageIO.read(backgroundfile.toFile());
    BufferedImage frontBuffImg = makeColorTransparent(frontImage, Color.WHITE);

    int width = Math.max(backgroundBuffImg.getWidth(), frontBuffImg.getWidth());
    int height = Math.max(backgroundBuffImg.getHeight(), frontBuffImg.getHeight());
    backgroundBuffImg = resize(backgroundBuffImg, width, height);
    //scaling front image
    int scaledWidth = (int) ((width));
    int scaledHeight = (int) ((height) * 1.02);
    frontBuffImg = resize(frontBuffImg, scaledWidth, scaledHeight);

    BufferedImage newImage = mergeImages(backgroundBuffImg, frontBuffImg);
    ImageIO.write(newImage, "PNG", outputFile.toFile());

    return Files.readAllBytes(outputFile);
}

public static BufferedImage resize(BufferedImage img, int width, int height) 
{
    if (img.getWidth() == width && img.getHeight() == height) {
        return img;
    } else {
        return Scalr.resize(img, width, height);
    }
}

public static BufferedImage mergeImages(BufferedImage background, BufferedImage front) {
    int width = background.getWidth();
    int height = background.getHeight();

    BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = newImage.getGraphics();
    g.drawImage(background, 0, 0, null);
    g.drawImage(front, 15, -10, background.getWidth(), background.getHeight(), 0, 0, width, height, null);
    return newImage;
}

在这里您可以看到完整的课程:https://pastebin.com/F4VrBwRv

0 个答案:

没有答案