package iDSS.utils;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.imageio.*;







public class ImageRW {



    public static Vector writeImgFile(BufferedImage bi) {

        int MINIMUM_IMAGE_SIZE = IDSSAppConstants.MINIMUM_IMAGE_SIZE;
        BufferedImage bi2 = null;

        if ((bi.getWidth() < MINIMUM_IMAGE_SIZE) && (bi.getHeight() < MINIMUM_IMAGE_SIZE)) {

            int longSide = Math.max(bi.getWidth(),bi.getHeight());
            int ratio = MINIMUM_IMAGE_SIZE / longSide;

            bi2 = new BufferedImage (bi.getWidth()*ratio,bi.getHeight()*ratio,BufferedImage.TYPE_INT_RGB);
            Graphics g2 = bi2.getGraphics();
            g2.drawImage(bi,0,0,bi2.getWidth(),bi2.getHeight(),0,0,bi.getWidth(),bi.getHeight(),null);

        }

        else {
            bi2 = bi;
        }


        File imgDir = new File(IDSSAppConstants.imgDir);
        if(!imgDir.exists())
            imgDir.mkdirs();

        File tempOutFile = new File(imgDir,FileNameDialog.getTempImgFileName());
        tempOutFile.deleteOnExit();

        if(tempOutFile.exists())
            tempOutFile.delete();


        try {
            ImageIO.write(bi2, "png", tempOutFile);
        }

        catch(javax.imageio.IIOException ie) {

            System.out.println("GridViewColtrol.writeImgFiles(), " + ie.toString());

        } //catch(javax.imageio.IIOException ie)

        Vector v = new Vector();
        v.add(tempOutFile.toString());
        v.add(new Integer(bi2.getWidth()));
        v.add(new Integer(bi2.getHeight()));

        System.out.println("GridManagerJBean.writeImgFile(), with, height : " + bi2.getWidth() + "," + bi2.getHeight());

        return v;

    } //public static Vector writeImgFile(BufferedImage bi)







    public static BufferedImage scaleImage(BufferedImage bi) {

        int minSize = IDSSAppConstants.MINIMUM_IMAGE_SIZE;

        BufferedImage bi2 = null;

        if ((bi.getWidth() < minSize) && (bi.getHeight() < minSize)) {

            int longSide = Math.max(bi.getWidth(),bi.getHeight());
            int ratio = minSize / longSide;

            bi2 = new BufferedImage (bi.getWidth()*ratio,bi.getHeight()*ratio,BufferedImage.TYPE_INT_RGB);
            Graphics g2 = bi2.getGraphics();
            g2.drawImage(bi,0,0,bi2.getWidth(),bi2.getHeight(),0,0,bi.getWidth(),bi.getHeight(),null);

        }

        else {
            bi2 = bi;
        }

        return bi2;

    } //public static BufferedImage scaleImage(BufferedImage bi)











} //public class ImageRW

