

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.image.codec.jpeg.*;

/** Class CapturingCanvas3D, using the instructions from the Java3D
 * FAQ pages on how to capture a still image in jpeg format.
 *
 */

public class CapturingCanvas3D extends Canvas3D  {

    /** This boolean indicates weither a JPEG has to be written
     */
    public boolean writeJPEG_;
    /** This integer represents the numbers of postswaps
     */
    private int postSwapCount_;
    /** This string holds the name of the JPEG file
     */
    private String  file;
    /** This String holds the path of the save directory
     */
    private String directory;

    /** This is the constructor of this class.  It extends Canvas3D and initialises
     * the default attributes
     * @param gc the Graphical configuration of this Canvas3D
     * @param file The destination file
     * @param directory The destination directory
     */
    public CapturingCanvas3D(GraphicsConfiguration gc, String file, String directory) {
        super(gc);
        postSwapCount_ = 0;
        this.file = file;
        this.directory = directory;
    }

    /** This method is called after each render cycle.  It is in this method
     * that the file will be captured and written
     */
    public void postSwap() {
        if(writeJPEG_) {
         //   System.out.println("Writing JPEG");
            GraphicsContext3D  ctx = getGraphicsContext3D();
            // The raster components need all be set!
            Raster ras = new Raster(
                   new Point3f(-1.0f,-1.0f,-1.0f),
                   Raster.RASTER_COLOR,
                   0,0,
                   200,200,
                   new ImageComponent2D(
                             ImageComponent.FORMAT_RGB,
                             new BufferedImage(200,200,
                                               BufferedImage.TYPE_INT_RGB)),
                   null);

            ctx.readRaster(ras);

            // Now strip out the image info
            BufferedImage img = ras.getImage().getImage();

            // write that to disk....
            try {
                FileOutputStream out = new FileOutputStream(directory + file + ".jpg");
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
                param.setQuality(0.9f,false); // 90% qualith JPEG
                encoder.setJPEGEncodeParam(param);
                encoder.encode(img);
                writeJPEG_ = false;
                out.close();
            } catch ( IOException e ) {
                System.out.println("I/O exception!");
            }
            postSwapCount_++;
        }
    }
}
