如何通过 java 将两个图像放在一个 canvas 中(不是 jframe)

How to place two images in one canvas through java (not jframe)

我只想将两张不同的图片放在一张 canvas 上,并在 Java 中将其制成 .jpg 文件。我只想制作结果文件,而不是 GUI。

我想用上面的两张图片制作一个如下所示的结果文件:

您可以使用BufferedImage将两个图像组合起来。以下代码显示了一个简单的实现:

public static void combineImages(String imagePath1, String imagePath2, String outputPath) throws IOException {
    int intervalWidth = 20; // The interval between two images
    BufferedImage image1 = ImageIO.read(new File(imagePath1));
    BufferedImage image2 = ImageIO.read(new File(imagePath2));
    int combinedWidth = image1.getWidth() + image2.getWidth() + intervalWidth;
    int combinedHeight = Math.max(image1.getHeight(), image2.getHeight());
    BufferedImage combined = new BufferedImage(combinedWidth, combinedHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = combined.createGraphics();
    g.setColor(Color.WHITE);
    // Fill the background with white
    g.fillRect(0, 0, combinedWidth, combinedHeight);
    // Draw the two images on the combined image
    g.drawImage(image1, 0, 0, null);
    g.drawImage(image2, image1.getWidth() + intervalWidth, 0, null);
    ImageIO.write(combined, "jpg", new File(outputPath));
}