Java Graphics How to - Paint two images to one image








Question

We would like to know how to paint two images to one image.

Answer

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
//from ww  w . j  a  v  a 2  s  .com
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedImage large = ImageIO.read(new File("images/a.jpg"));
    BufferedImage small = ImageIO.read(new File("images/b.jpg"));
    
    int w = large.getWidth();
    int h = large.getHeight();
    int type = BufferedImage.TYPE_INT_RGB;
    
    BufferedImage image = new BufferedImage(w, h, type);
    Graphics2D g2 = image.createGraphics();
    g2.drawImage(large, 0, 0, null);
    g2.drawImage(small, 10, 10, null);
    g2.dispose();
    ImageIO.write(image, "jpg", new File("new.jpg"));
    
    JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
        JOptionPane.PLAIN_MESSAGE);
  }
}