package yi.util.io;

import java.awt.image.*;
import java.awt.*;
import java.io.*;

/**
 * Image IO Utilities
 */

public class ImageIOUtil{

  public static void write(String filename, String type, int[] pixels, int w, int h) throws IOException{
    BufferedImage bi = new BufferedImage(w, h,
                                         BufferedImage.TYPE_INT_ARGB);
    bi.setRGB(0, 0, w, h, pixels, 0, w);
    java.io.File f = new java.io.File(filename);
    javax.imageio.ImageIO.write(bi, type, f);
  }

  public static int[] read(String img_name, Dimension d) throws IOException{
    try {
      BufferedImage image = javax.imageio.ImageIO.read(new java.io.File(
          img_name));
      return getPixels(image, d);
    } catch (IOException e) {
      System.err.println("error to read " + img_name);
      throw e;
    }
  }

  /**
   * 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();
      if (d != null) d.setSize(pg.getWidth(), pg.getHeight());
      return pixels;
  }

}