I just want to place two different images on one canvas and make it a .jpg file in Java. I just want to make a resulting file, not a GUI.
I want to make a result file like below with both images above:
CodePudding user response:
You can use BufferedImage
to combine the two images. The following code shows a simple implementation.
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));
}