

package jogltest;

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

import javax.imageio.ImageIO;
import javax.media.opengl.GL2;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLOffscreenAutoDrawable;
import javax.media.opengl.GLProfile;

import com.jogamp.opengl.util.awt.AWTGLReadBufferUtil;

public class TestOffScreen {

	public static void main(String[] args) {

		GL2 gl2;
		
		GLDrawableFactory fac = GLDrawableFactory.getFactory(GLProfile.getDefault());
		GLCapabilities glCap = new GLCapabilities(GLProfile.getDefault());
		// Without line below, there is an error on Windows.
		glCap.setDoubleBuffered(false);
		//makes a new buffer 100x100
		GLOffscreenAutoDrawable buf = fac.createOffscreenAutoDrawable(null, glCap, null, 100, 100);
		GLContext context =  buf.createContext(null); 
		context.makeCurrent();
		gl2 = context.getGL().getGL2();
		gl2.glViewport(0, 0, 100, 100);
		gl2.glShadeModel(GL2.GL_SMOOTH);
		gl2.glClearColor(1.0f, 0.80f, 0.80f, 1);    // This Will Clear The Background Color
		gl2.glClearDepth(1.0);                    // Enables Clearing Of The Depth Buffer
		gl2.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
		gl2.glLoadIdentity();                    // Reset The Projection Matrix
		AWTGLReadBufferUtil agb = new AWTGLReadBufferUtil(buf.getGLProfile(), true);
		BufferedImage image = agb.readPixelsToBufferedImage(context.getGL(), true);
		try {
			ImageIO.write(image, "PNG", new File("test.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		context.destroy();
		buf.destroy();
		System.out.println("Done!");
	}

}
