import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
import com.sun.image.codec.jpeg.*;

public class JavaPicture extends JFrame
{
    public JPanel canvas;
    public String filename;
    public Image img;
    private BufferedImage bimg;
    public Graphics2D bimg2D;
    public int [] pixels;
    private int w;
    private int h;
    
    /**
     * Public constructor 
     * <BR>
     */
    public JavaPicture()
    {
		canvas = null;
    }

	/**
     * Makes the image on the JPanel
     *
     * @return JPanel canvas
     */
    public JPanel getCanvas()
    {
		if(canvas == null)
			canvas = new JPanel()
       		{
            	public void paintComponent(Graphics g) 
            	{
            		super.paintComponent(g);
            		Graphics2D g2 = (Graphics2D)g;
            		try
            		{
            			g2.drawImage(bimg, null, 0, 0);
            		}
            		catch(NullPointerException e)
            		{
            			
            			//Creates an OK button
						Object[] options = { "OK" };
						//Creates the string to print
						String information="There is no picture to display";
			                  
			
						//Creates a JOptionPane with the instructions and Icon
            			JOptionPane.showOptionDialog(null, information, "Picture Error", 
            					JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
            					null, options, options[0]);
            			
            		}
            	}
        	};
		return canvas;
    }
    
    /**
     * Sets the filename and the title of the window
     *
     * @param String f
     */
    public void setFilename( String f)
    {
  		filename = f;
		this.setTitle(f);
    }
	
	/**
     * Gets the file name
     *
     * @return String filename
     */
    public String getFileName()
    {
  		return filename;
    }

	/**
     * Returns an updated file name with the proper start
     *
     * @param String filename
     * @return URL finalString
     */
	public URL getURL (String filename)
    {
    	String finalString = filename;
  		if (! (filename.startsWith("http://")))
	    {
	    	finalString = ("file://"+filename);
	    }
	
		try
		{
			return new URL(finalString);
    	}
    	catch(java.net.MalformedURLException e)
    	{
	    	return null;
		}
    }
    
    /**
     * Returns 1 of success 0 for failure
     *
     * @param String filename
     * @return int 
     */
    public int loadImage(String filename)
    {
		boolean foundFile;
		setFilename(filename);
		URL url = getURL(filename);
		
		if (url == null)
		{
			return 0;
		}
		//System.out.println(url);
		//System.out.println(url.getRef());
		ImageIcon imgIcon	= new ImageIcon(filename);
	
		w = imgIcon.getIconWidth();	// width
	    h = imgIcon.getIconHeight();	// height
	    foundFile = (w != -1); 
		if (!foundFile)
		{ 
	    	return 0;
		}
	
		img = imgIcon.getImage();
	
		try 
		{
	    	MediaTracker tracker = new MediaTracker(this);
	    	tracker.addImage(img, 0);
	    	tracker.waitForID(0);
		}
		catch ( Exception e ) 
		{
		}
	
		createNewImage(h, w);
		if (foundFile) 
		{
			bimg2D.drawImage(img,0,0,this);
		}
		
		return 1;
    }
    
    /**
     * Used to create zoomed images from 
     * already loaded images
     *
     * @param String filename
     * @return int 
     */
    public int zoomLoadImage(Image zoomImg, int width, int height)
    {
		int h=height;
		int w=width;
		img = zoomImg;
	
		try 
		{
	    	MediaTracker tracker = new MediaTracker(this);
	    	tracker.addImage(img, 0);
	    	tracker.waitForID(0);
		}
		catch ( Exception e ) 
		{
		}
	
		createNewImage(h, w);
		
		bimg2D.drawImage(img,0,0,this);
		
		return 1;
    }
    /**
     * Creates a new Image of height and width
     * 
     * @param int h
     * @parma int w
     */
    public void createNewImage(int h, int w)
    {
		bimg = null;
		bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		bimg2D = bimg.createGraphics();
		this.getCanvas().setPreferredSize(new Dimension(w,h));
		super.getContentPane().add(getCanvas());
		super.setResizable(false);
		super.pack();
    }
    
    public void dispose()
    {
	System.out.println("Disposing JavaPicture");
	super.dispose();
	bimg.flush();
	bimg2D.dispose();
    }


    /**
     * Saves the image to file 
     *
     * @param String newfilename
     */
    public void saveImage(String newfilename) throws java.io.IOException
    {
		FileOutputStream out;
		JPEGImageEncoder jpeg;

		try 
		{
			out = new FileOutputStream(newfilename);
		}
		catch (Exception e)
	    {
	    	System.out.println("Sorry -- that filename ("+newfilename+") isn't working");
	    	return;
	    }

		try 
		{
			jpeg = JPEGCodec.createJPEGEncoder(out);
		}
		catch (Exception e)
	    {
	    	System.out.println("Unable to create a JPEG encoder");
	    	return;
	    }

		JPEGEncodeParam param =
	    			jpeg.getDefaultJPEGEncodeParam(bimg);
		param.setQuality(1.0f,true);
		jpeg.encode(bimg,param);
		out.close();
    }
    
    /**
     * accessor width
     *
     * @return int w
     */
    public int getWidth()
    {
  		return w;
    }
    
    /**
     * accessor img
     *
     * @return image img
     */
    public Image getImage()
    {
  		return img;
    }
	
	 /**
     * accessor height
     *
     * @return int h
     */
    public int getHeight()
    {
  		return h;
    }
	
	/**
     * Returns a pixel
     *
     * @param int x
     * @param int y
     * @return int pixel
     */
    public int getBasicPixel(int x, int y)
    {
  		// to access pixel at row 'j' and column 'i' from the upper-left corner of
		// image.
		return bimg.getRGB(x,y);
    }
	
	/**
     * Sets a pixel
     *
     * @param int x
     * @param int y
     * @param int rgb
     */
    public void setBasicPixel(int x, int y, int rgb)
    {
  		bimg.setRGB(x,y,rgb);
    }
    
    /**
     * Returns a JavaPixel
     * 
     * @param int x
     * @param int y
     * @return JavaPixel
     */
    public JavaPixel getPixel(int x, int y)
    {
  		return new JavaPixel(this,x,y);
    }

	/**
     * Shows the image in a window
     */
    public void show()
    {
		super.show();
		Dimension d = getSize();
		String title = getTitle();
		int minWidth = 100 + 6 * title.length();
	
		if (d.getWidth() < minWidth)
		{
	    	super.setSize(new Dimension(minWidth, (int)d.getHeight()));
	    }
    }
    
    /**
     * Returns a BufferedImage
     * 
     * @return BufferedImage bimg
     */
    public BufferedImage getBufferedImage()
    {
    	return bimg;
    }
    
    /**
     * Test Main
     */
    public static void main( String args[] )
    {
		JavaPicture p = new JavaPicture();
	
		p.loadImage("\\School Work\\Mediacomp\\temp.jpg");
		System.out.println("Width is "+p.getWidth());
		System.out.println("Height is "+p.getHeight());
    	p.show();
    }
}