Thursday, April 15, 2021

[Java Code Sample] Combine multiple buffered images into a single image

 

Here's a sample code to merge multiple images into a single image.


There are two versions.  

The version one is to place two images side by side and merge them as a single image. 

The version two is to merge two images on the same spot.


If you want to follow the process step by step, please check my video tutorial:




Code:



import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
	
	BufferedImage image1;
	BufferedImage image2;
	
	public static void main(String[] args){

		new Main();
	}
	public Main() {
		

		JFrame window = new JFrame();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		BufferedImage combinedImage;
		
		try {
			// VERSION 1
			image1 = ImageIO.read(getClass().getClassLoader().getResource("town 800x600.png"));
			image2 = ImageIO.read(getClass().getClassLoader().getResource("girl 800x600.png"));
			
			combinedImage = new BufferedImage(800,600, BufferedImage.TYPE_INT_ARGB);
			
			Graphics2D g = combinedImage.createGraphics();
			
			g.drawImage(image1, 0, 0, null);
			g.drawImage(image2, 0, 0, null);
			// VERSION 1 END
			
			// VERSION 2
//			image1 = ImageIO.read(getClass().getClassLoader().getResource("11C.png"));
//			image2 = ImageIO.read(getClass().getClassLoader().getResource("12C.png"));
//			
//			int width = image1.getWidth() + image2.getWidth();
//			int height = Math.max(image1.getHeight(), image2.getHeight());
//			
//			combinedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
//			
//			Graphics2D g = combinedImage.createGraphics();
//			
//			g.drawImage(image1, 0, 0, null);
//			g.drawImage(image2, image1.getWidth(), 0, null);
			// VERSION 2 END
			
			g.dispose();
			
			JLabel label = new JLabel();
			window.add(label);
			label.setIcon(new ImageIcon(combinedImage));
			
            // Export the combined image to desktop
			try {
				ImageIO.write(combinedImage, "PNG", new File("C:\\Users\\User\\Desktop\\combinedImage.png"));
			}catch(IOException e) {
				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		window.pack();
		window.setVisible(true);
		
	}
}








Result:

Version 1


+





Version 2











No comments:

Post a Comment