Save png files without AWT

I wanted to remove the AWT dependancy from Snowman Village, but it uses ImageIO for saving the screenshots. Kevglass handily pointed me towards this png encoder, which has minimal dependancies. It wasn’t too much trouble to modify it to remove the BufferedImage use, so the version below will happily save png images without any annoying AWT dependancy. I also added an option to encode the image flipped vertically, so you can just hand it data straight from an OpenGL pixel grab.

You may also want the handy Screenshot class, which makes taking screenshots of LWJGL apps a breeze.

package net.orangytang.evolved;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;

public class Screenshot
{

	/** Captures a portion of the current OpenGL display, then saves it out in png format */
	public static void takeScreenshot(int x, int y, int width, int height, File outputFile)
	{
		IntBuffer screenContents = ByteBuffer.allocateDirect(width * height * 4).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
		GL11.glReadPixels(x, y, width, height, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, screenContents);
		
		int[] pixels = new int[width * height];
		screenContents.get(pixels);
		
		PngEncoder png = new PngEncoder(width, height, pixels);
		png.setFlipped(true);
		png.writeImage(outputFile);
	}
}

I’ve had to attach the source as a txt file because the stupid forum won’t allow .java files to be attached, and otherwise it exceedes the post size limit. ::slight_smile:
PngEncoder - accepts an int[] containing 0xAARRGGBB pixels, and encodes them into a png

The original code was LGPL, but frankly I don’t know how that applies when someone releases something as a single-file source-only distribution. Either way, the code above is free for any kind of use or modification. Enjoy.

Nice one OT :slight_smile: Ideal solution.

Kev