package yi.util.io;

import java.io.*;
import java.awt.*;
import java.awt.Image;
import java.awt.image.*;
import Acme.JPM.Decoders.*;
import javax.media.jai.*;
import com.sun.media.jai.codec.*;

/**
 * Image file Reader
 * Title:        Object Image Generation
 * Description:  This project provides the required utilities to construct Object Images.  An Object Image is an image containing one or several predefined object sketch.  This kind of image is suitable to be used as experiment image when testing a learning algorithm.
 * Copyright:    Copyright (c) 2002
 * Company:      University of Washington
 * @author Yi Li
 * @version 1.0
 */

public class ImageReader {
    /**
     * Read a image from a given image file name
     * PREREQUIREMENT: image must exist
     *                 not from an applet
     */
    public static Image readImageFile(String imageName) throws IOException{
        Image im = null;

        if (imageName.endsWith(".ppm") || imageName.endsWith(".pgm")) {   // handle ppm file
            DataInputStream in= new DataInputStream(
                new FileInputStream(imageName));
            PpmDecoder ppmd= new PpmDecoder(in);

            Toolkit tk= Toolkit.getDefaultToolkit();
            im= tk.createImage(ppmd);
        }
        else {
            im= Toolkit.getDefaultToolkit().getImage(imageName);
        }
        return im;
    }

    /**
     * get the RGB array of an image
     * return a 1-D array.  every pixel is represented in 4 bytes (an integer)
     * the four bytes carry alpha, red, green, blue information from the most
     * significant byte to the least
     * @param d return Dimension information
     */
    public static int[] getPixels(Image i, Dimension d) {
        PixelGrabber pg = new PixelGrabber(i,0,0,-1,-1,true);
        try {
            pg.grabPixels();
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
            System.exit(0);
        }

        int[] pixels = (int[])pg.getPixels();
        d.setSize(pg.getWidth(), pg.getHeight());
        return pixels;
    }

    public static int[] getPixels(Image i, int w, int h) {
      return getPixels(i, new Dimension(w, h));
    }

    public static BufferedImage JAIReadImage(String filename) {
      RenderedOp op = JAI.create("FileLoad", filename);
      PlanarImage planarImage = op.createInstance();
      return planarImage.getAsBufferedImage();
    }

    public static void JAIWriteImage(int[] pixels, int width, int height, String filename, String format) {
      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      image.setRGB(0, 0, width, height, pixels, 0, width);
      RenderedOp op = JAI.create("filestore", image, filename, format);

    }
}
