ImagePanel.java

ImagePanel is intended as a service class for image processing, but includes a main program that displays an image chosen from the command line or a JFileChooser.

C:\ece538\impro1>java ImagePanel bld.jpg
Image: bld.jpg
size: 327 x 215


ImagePanel.java

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.net.URL;

public class ImagePanel  extends JPanel {
    BufferedImage img;
    String title;
    double scl;

   public ImagePanel() {
	title="Blank";
	scl = 1.0;
	img = null;
}

    public ImagePanel(BufferedImage img, String title) {
	this.img = img;
	this.title = title;
	setScale();
   }

   public ImagePanel(String filename) {
	File f = new File(filename);
	if (f.exists()) readImage(filename);
	else {
		URL imageSrc = getClass().getResource(filename);
		if (imageSrc!=null) readImage(imageSrc);
		else {
		   System.err.println("file not found: " + filename);
		   System.exit(-1);
		}
	}
	title = filename;
	setScale();
  }

   public ImagePanel(File f) {
	  readImage(f);
	  title = f.getName();
	 setScale();
   }

   public void setMag(int mag) {
	scl = mag;
	repaint();
   }


static JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));

static File choose_image() {
            fc.setAcceptAllFileFilterUsed(false);
            fc.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
            fc.setAcceptAllFileFilterUsed(true);

	int result = fc.showOpenDialog(null);
	if (result== JFileChooser.APPROVE_OPTION)
		return fc.getSelectedFile();
	else return null;	    
}

private static String getFileExtension(File file) {
        String name = file.getName();
        int loc = name.lastIndexOf(".");
        if (loc>0) return name.substring(loc+1);
        else return "";

}

    public void saveFile(String name) {
	fc.setSelectedFile(new File(name));
	int result = fc.showSaveDialog(null);
	if (result != JFileChooser.APPROVE_OPTION) return;
	File f = fc.getSelectedFile();
                  if (f.exists()) {
       	    result = JOptionPane.showConfirmDialog(this, "Overwrite existing file?","Warning",
       		 JOptionPane.WARNING_MESSAGE);
  	     if (result==JOptionPane.CANCEL_OPTION)  return;
	}		
	String ext = getFileExtension(f);
	writeImage(fc.getSelectedFile(), ext);
    }

   public int getImageHeight() {
	return img.getHeight();
   }

   
   public void setScale()
   {
	if (img==null) return;
	int w = img.getWidth();
	int h = img.getHeight();

	Toolkit toolkit =  Toolkit.getDefaultToolkit();
   	Dimension dim = toolkit.getScreenSize();
 	//System.out.format("screen size: %d x %d %n",dim.width,dim.height);

	//System.out.format("image size %d x %d%n",w,h);
	scl = 1.0;
	if (w<128) {
		scl = (double) 128/w;
	}
	else {
		scl = Math.min((double) (dim.width-200)/w, (double) (dim.height-200)/h);
		if (scl>1.0) scl = 1.0;
	}
   }

    public void info() {
       System.out.println("Image: " + title);
       if (img==null) return;
       System.out.format("size: %d x %d%n",img.getWidth(),img.getHeight());
       if (scl!=1.0) System.out.format("scale %g%n",scl);
   }

   public void readImage(URL src) {
	try {
	   img = ImageIO.read(src);
       } catch (IOException e) {
		System.out.println(e.getMessage());
		System.exit(-1);
       }
   }

   public void readImage(File f) {
       try {
           img = ImageIO.read(f);
       } catch (IOException e) {
		System.out.println(e.getMessage());
		System.exit(-1);
       }
   }	
    

    public void readImage(String filename) {
       try {
           img = ImageIO.read(new File(filename));
       } catch (IOException e) {
		//System.out.println(e); // e.getMessage());
		System.out.println(filename + " not found");
		System.exit(-1);
       }
    }

    public void writeImage(String filename) {
		File f = new File(filename);
		String ext = getFileExtension(f);
		writeImage(f,ext);
    }

    public void writeImage(File file, String format) {
		try {
			ImageIO.write(img, format, file);
		} catch (IOException e) {
			System.out.println("image write failed");
			System.out.println(e);
			System.exit(-1);
		}
	}

    public Dimension getPreferredSize() {
	int w, h;
	w = 240;
	h = 180;	
        if (img != null) {
	   w = (int) (scl*img.getWidth());
	   h = (int) (scl*img.getHeight());
	}
	//System.out.format("preferred size: %d x %d%n",w,h);
        return new Dimension(w,h);
    }


    public void paintComponent(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;
	super.paintComponent(g2);
	if (img==null) return;
        if (scl==1.0) g2.drawImage(img, 0, 0, null);
        else   g2.drawImage(img, AffineTransform.getScaleInstance(scl, scl), null);
    }

     public void makeFrame() {
	EventQueue.invokeLater(() -> {
		JFrame app = new JFrame(title);
		app.add(this);
		app.pack();
		app.setLocation(100,100);
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		app.setVisible(true);
	});
   }

    public static void main(String[] args) {
	ImagePanel f1 = null;
	String filename = "robin2.jpg";
	if (args.length>0) {
		filename = args[0];
		f1 = new ImagePanel(filename);
	}
	else {
	    File f = ImagePanel.choose_image();
	    if (f!=null) f1 = new ImagePanel(f);
	    else f1 = new ImagePanel();
        }
	
	f1.info();
	f1.makeFrame();

    }
}


Maintained by John Loomis, updated Wed Mar 18 15:37:49 2020