How to combine multiple PNGs into one big PNG file?

soc picture soc · Oct 13, 2010 · Viewed 55.3k times · Source

I have approx. 6000 PNG files (256*256 pixels) and want to combine them into a big PNG holding all of them programmatically.

What's the best/fastest way to do that?

(The purpose is printing on paper, so using some web-technology is not an option and having one, single picture file will eliminate many usage errors.)

I tried fahd's suggestion but I get a NullPointerException when I try to create a BufferedImage with 24576 pixels wide and 15360 pixels high. Any ideas?

Answer

dogbane picture dogbane · Oct 13, 2010

Create a large image which you will write to. Work out its dimensions based on how many rows and columns you want.

    BufferedImage result = new BufferedImage(
                               width, height, //work these out
                               BufferedImage.TYPE_INT_RGB);
    Graphics g = result.getGraphics();

Now loop through your images and draw them:

    for(String image : images){
        BufferedImage bi = ImageIO.read(new File(image));
        g.drawImage(bi, x, y, null);
        x += 256;
        if(x > result.getWidth()){
            x = 0;
            y += bi.getHeight();
        }
    }

Finally write it out to file:

    ImageIO.write(result,"png",new File("result.png"));