All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ij.io.Opener Maven / Gradle / Ivy

Go to download

ImageJ is an open source Java image processing program inspired by NIH Image for the Macintosh.

The newest version!
package ij.io;
import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.plugin.frame.*;
import ij.plugin.*;
import ij.text.TextWindow;
import ij.util.Java2;
import ij.measure.ResultsTable;
import ij.macro.Interpreter;
import ij.util.Tools;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.event.KeyEvent;
import javax.imageio.ImageIO;
import java.lang.reflect.Method;

/** Opens tiff (and tiff stacks), dicom, fits, pgm, jpeg, bmp or
	gif images, and look-up tables, using a file open dialog or a path.
	Calls HandleExtraFileTypes plugin if the file type is unrecognised. */
public class Opener {

	public static final int UNKNOWN=0,TIFF=1,DICOM=2,FITS=3,PGM=4,JPEG=5,
		GIF=6,LUT=7,BMP=8,ZIP=9,JAVA_OR_TEXT=10,ROI=11,TEXT=12,PNG=13,
		TIFF_AND_DICOM=14,CUSTOM=15, AVI=16, OJJ=17, TABLE=18, RAW=19; // don't forget to also update 'types'
	public static final String[] types = {"unknown","tif","dcm","fits","pgm",
		"jpg","gif","lut","bmp","zip","java/txt","roi","txt","png","t&d","custom","ojj","table","raw"};
	private static String defaultDirectory = null;
	private int fileType;
	private boolean error;
	private boolean isRGB48;
	private boolean silentMode;
	private String omDirectory;
	private File[] omFiles;
	private static boolean openUsingPlugins;
	private static boolean bioformats;
	private String url;
	private boolean useHandleExtraFileTypes;
	private boolean doNotUseBioFormats;

	static {
		Hashtable commands = Menus.getCommands();
		bioformats = commands!=null && commands.get("Bio-Formats Importer")!=null;
	}

	public Opener() {
	}

	/**
	 * Displays a file open dialog box and then opens the tiff, dicom, 
	 * fits, pgm, jpeg, bmp, gif, lut, roi, or text file selected by 
	 * the user. Displays an error message if the selected file is not
	 * in a supported format. This is the method that
	 * ImageJ's File/Open command uses to open files.
	 * @see ij.IJ#open
	 * @see ij.IJ#open(String)
	 * @see ij.IJ#openImage
	 * @see ij.IJ#openImage(String)
	*/
	public void open() {
		OpenDialog od = new OpenDialog("Open", "");
		String directory = od.getDirectory();
		String name = od.getFileName();
		if (name!=null) {
			String path = directory+name;
			error = false;
			open(path);
			if (!error) Menus.addOpenRecentItem(path);
		}
	}

	/**
	 * Opens and displays the specified tiff, dicom, fits, pgm, jpeg, 
	 * bmp, gif, lut, roi, or text file. Displays an error message if 
	 * the file is not in a supported format.
	 * @see ij.IJ#open(String)
	 * @see ij.IJ#openImage(String)
	*/
	public void open(String path) {
		boolean isURL = path.contains("://") || path.contains("file:/");
		if (isURL && isText(path)) {
			openTextURL(path);
			return;
		}
		if (path.endsWith(".jar") || path.endsWith(".class")) {
				(new PluginInstaller()).install(path);
				return;
		}
		path = makeFullPath(path);
		if (!silentMode)
			IJ.showStatus("Opening: " + path);
		long start = System.currentTimeMillis();
		ImagePlus imp = null;
		if (path.endsWith(".txt"))
			this.fileType = JAVA_OR_TEXT;
		else {
			useHandleExtraFileTypes = true;
			imp = openImage(path);
		}
		if (imp==null && isURL)
			return;
		if (imp!=null) {
			WindowManager.checkForDuplicateName = true;
			if (isRGB48)
				openRGB48(imp);
			else
				imp.show(getLoadRate(start,imp));
		} else {
			switch (this.fileType) {
				case LUT:
					imp = (ImagePlus)IJ.runPlugIn("ij.plugin.LutLoader", path);
					if (imp.getWidth()!=0)
						imp.show();
					break;
				case ROI:
					IJ.runPlugIn("ij.plugin.RoiReader", path);
					break;
				case JAVA_OR_TEXT: case TEXT:
					if (IJ.altKeyDown()) { // open in TextWindow if alt key down
						new TextWindow(path,400,450);
						IJ.setKeyUp(KeyEvent.VK_ALT);
						break;
					}
					File file = new File(path);
					int maxSize = 250000;
					long size = file.length();
					if (size>=28000) {
						String osName = System.getProperty("os.name");
						if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equals("Windows Me"))
							maxSize = 60000;
					}
					if (size64)
							path = (new File(path)).getName();
						if (path.length()<=64)
								msg += " \n"+path;
					}
					if (openUsingPlugins && msg.length()>20)
						msg += "\n \nNOTE: The \"OpenUsingPlugins\" option is set.";
					IJ.wait(IJ.isMacro()?500:100); // work around for OS X thread deadlock problem
					IJ.error("Opener", msg);
					error = true;
					break;
			}
		}
	}
		
	/** Displays a JFileChooser and then opens the tiff, dicom, 
		fits, pgm, jpeg, bmp, gif, lut, roi, or text files selected by 
		the user. Displays error messages if one or more of the selected 
		files is not in one of the supported formats. This is the method
		that ImageJ's File/Open command uses to open files if
		"Open/Save Using JFileChooser" is checked in EditOptions/Misc. */
	public void openMultiple() {
		LookAndFeel saveLookAndFeel = Java2.getLookAndFeel();
		Java2.setSystemLookAndFeel();
		// run JFileChooser in a separate thread to avoid possible thread deadlocks
		try {
			EventQueue.invokeAndWait(new Runnable() {
				public void run() {
					JFileChooser fc = new JFileChooser();
					fc.setMultiSelectionEnabled(true);
					fc.setDragEnabled(true);
					fc.setTransferHandler(new DragAndDropHandler(fc));
					File dir = null;
					String sdir = OpenDialog.getDefaultDirectory();
					if (sdir!=null)
						dir = new File(sdir);
					if (dir!=null)
						fc.setCurrentDirectory(dir);
					if (IJ.debugMode) IJ.log("Opener.openMultiple: "+sdir+" "+dir);
					int returnVal = fc.showOpenDialog(IJ.getInstance());
					if (returnVal!=JFileChooser.APPROVE_OPTION)
						return;
					omFiles = fc.getSelectedFiles();
					if (omFiles.length==0) { // getSelectedFiles does not work on some JVMs
						omFiles = new File[1];
						omFiles[0] = fc.getSelectedFile();
					}
					omDirectory = fc.getCurrentDirectory().getPath()+File.separator;
				}
			});
		} catch (Exception e) {}
		if (omDirectory==null) return;
		OpenDialog.setDefaultDirectory(omDirectory);
		for (int i=0; i6)
			return true;  // no extension
		else
			return false;
	}
	
	/** Opens the specified file and adds it to the File/Open Recent menu.
		Returns true if the file was opened successfully.  */
	public boolean openAndAddToRecent(String path) {
		open(path);
		if (!error)
			Menus.addOpenRecentItem(path);
		return !error;
	}

	/**
	 * Attempts to open the specified file as a tiff, bmp, dicom, fits,
	 * pgm, gif or jpeg image. Returns an ImagePlus object if successful.
	 * Modified by Gregory Jefferis to call HandleExtraFileTypes plugin if 
	 * the file type is unrecognised.
	 * @see ij.IJ#openImage(String)
	*/
	public ImagePlus openImage(String directory, String name) {
		ImagePlus imp;
		FileOpener.setSilentMode(silentMode);
		if (directory.length()>0 && !(directory.endsWith("/")||directory.endsWith("\\")))
			directory += Prefs.separator;
		OpenDialog.setLastDirectory(directory);
		OpenDialog.setLastName(name);
		String path = directory+name;
		this.fileType = getFileType(path);
		if (IJ.debugMode) IJ.log("openImage: \""+types[this.fileType]+"\", "+path);
		switch (this.fileType) {
			case TIFF:
				imp = openTiff(directory, name);
				return imp;
			case DICOM: case TIFF_AND_DICOM:
				imp = (ImagePlus)IJ.runPlugIn("ij.plugin.DICOM", path);
				if (imp.getWidth()!=0) return imp; else return null;
			case FITS:
				imp = (ImagePlus)IJ.runPlugIn("ij.plugin.FITS_Reader", path);
				if (imp.getWidth()!=0) return imp; else return null;
			case PGM:
				imp = (ImagePlus)IJ.runPlugIn("ij.plugin.PGM_Reader", path);
				if (imp.getWidth()!=0) {
					if (imp.getStackSize()==3 && imp.getBitDepth()==16)
						imp = new CompositeImage(imp, IJ.COMPOSITE);
					return imp;
				} else
					return null;
			case JPEG:
				imp = openJpegOrGif(directory, name);
				if (imp!=null&&imp.getWidth()!=0) return imp; else return null;
			case GIF:
				imp = (ImagePlus)IJ.runPlugIn("ij.plugin.GIF_Reader", path);
				if (imp!=null&&imp.getWidth()!=0) return imp; else return null;
			case PNG: 
				imp = openUsingImageIO(directory+name);
				if (imp!=null&&imp.getWidth()!=0) return imp; else return null;
			case BMP:
				imp = (ImagePlus)IJ.runPlugIn("ij.plugin.BMP_Reader", path);
				if (imp.getWidth()!=0) return imp; else return null;
			case ZIP:
				return openZip(path);
			case AVI:
				AVI_Reader reader = new AVI_Reader();
				reader.setVirtual(true);
				reader.displayDialog(!IJ.macroRunning());
				reader.run(path);
				return reader.getImagePlus();
			case JAVA_OR_TEXT:
				if (name.endsWith(".txt"))
					return openTextImage(directory,name);
				else
					return null;
			case UNKNOWN: case TEXT:
				imp = null;
				if (name.endsWith(".lsm"))
					useHandleExtraFileTypes = true; // use LSM_Reader to opem .lsm files
				if (!useHandleExtraFileTypes)
					imp = openUsingBioFormats(path);
				useHandleExtraFileTypes = false;
				if (imp!=null)
					return imp;
				else
					return openUsingHandleExtraFileTypes(path);
			default:
				return null;
		}
	}
	
	public ImagePlus openTempImage(String directory, String name) {
		ImagePlus imp = openImage(directory, name);
		if (imp!=null)
			imp.setTemporary();
		return imp;
	}
	
	// Call HandleExtraFileTypes plugin to see if it can handle unknown formats
	// or files in TIFF format that the built in reader is unable to open.
	private ImagePlus openUsingHandleExtraFileTypes(String path) {
		File f = new File(path);
		if (!f.exists())
			return null;
		int nImages = WindowManager.getImageCount();
		int[] wrap = new int[] {this.fileType};
		ImagePlus imp = openWithHandleExtraFileTypes(path, wrap);
		if (imp!=null && imp.getNChannels()>1)
			imp = new CompositeImage(imp, IJ.COLOR);
		this.fileType = wrap[0];
		if (imp==null && (this.fileType==UNKNOWN||this.fileType==TIFF) && WindowManager.getImageCount()==nImages)
			IJ.error("Opener", "Unsupported format or file not found:\n"+path);
		return imp;
	}
	
	String getPath() {
		OpenDialog od = new OpenDialog("Open", "");
		String dir = od.getDirectory();
		String name = od.getFileName();
		if (name==null)
			return null;
		else
			return dir+name;
	}

	/** Opens the specified text file as a float image. */
	public ImagePlus openTextImage(String dir, String name) {
		String path = dir+name;
		TextReader tr = new TextReader();
		ImageProcessor ip = tr.open(path);
		return ip!=null?new ImagePlus(name,ip):null;
	}

	/**
	 * Attempts to open the specified url as a tiff, zip compressed tiff, 
	 * dicom, gif or jpeg. Tiff file names must end in ".tif", ZIP file names 
	 * must end in ".zip" and dicom file names must end in ".dcm". Returns an 
	 * ImagePlus object if successful.
	 * @see ij.IJ#openImage(String)
	*/
	public ImagePlus openURL(String url) {
		url = updateUrl(url);
		if (IJ.debugMode) IJ.log("OpenURL: "+url);
		ImagePlus imp = openCachedImage(url);
		if (imp!=null)
			return imp;
		try {
			String name = getUrlName(url);
			if (url.indexOf(" ")!=-1)
				url = url.replaceAll(" ", "%20");
			URL u = new URL(url);
			IJ.showStatus(""+url);
			String lurl = url.toLowerCase(Locale.US);
			if (lurl.endsWith(".tif")) {
				this.url = url;
				imp = openTiff(u.openStream(), name);
			} else if (lurl.endsWith(".zip"))
				imp = openZipUsingUrl(u);
			else if (lurl.endsWith(".jpg") || lurl.endsWith(".jpeg") || lurl.endsWith(".gif")||lurl.contains(".jpg?")||lurl.contains(".jpeg?"))
				imp = openJpegOrGifUsingURL(name, u);
			else if (lurl.endsWith(".dcm") || lurl.endsWith(".ima")) {
				imp = (ImagePlus)IJ.runPlugIn("ij.plugin.DICOM", url);
				if (imp!=null && imp.getWidth()==0) imp = null;
			} else if (lurl.endsWith(".png")||lurl.contains(".png?"))
				imp = openPngUsingURL(name, u);
			else {
				URLConnection uc = u.openConnection();
				String type = uc.getContentType();
				if (type!=null && (type.equals("image/jpeg")||type.equals("image/gif")))
					imp = openJpegOrGifUsingURL(name, u);
				else if (type!=null && type.equals("image/png"))
					imp = openPngUsingURL(name, u);
				else
					imp = openWithHandleExtraFileTypes(url, new int[]{0});
			}
			IJ.showStatus("");
			return imp;
		} catch (Exception e) {
			String msg = e.getMessage();
			if (msg==null || msg.equals(""))
				msg = "" + e;
			msg += "\n"+url;
			IJ.error("Open URL", msg);
			return null;
		} 
	}
	
	private String getUrlName(String url) {
		String origUrl = url;
		String name = "";
		int ndx = url.lastIndexOf(".jpeg?");
		if (ndx>0)
			url = url.substring(0, ndx+5);
		else {
			ndx = url.lastIndexOf(".jpg?");
			if (ndx==-1)
				ndx = url.lastIndexOf(".png?");
			if (ndx>0)
				url = url.substring(0, ndx+4);
		}
		int index = url.lastIndexOf('/');
		if (index==-1)
			index = url.lastIndexOf('\\');
		if (index>0)
			name = url.substring(index+1);
		else
			throw new IllegalArgumentException("Invalid URL: "+url);
		return name;
	}
	
	/** Can't open imagej.nih.gov URLs due to encryption so redirect to imagej.net mirror. */
	public static String updateUrl(String url) {
		if (url==null || !url.contains("nih.gov"))
			return url;
		if (IJ.isJava18())
			url = url.replace("http:", "https:");
		else {
			url = url.replace("imagej.nih.gov/ij", "imagej.net");
			url = url.replace("rsb.info.nih.gov/ij", "imagej.net");
			url = url.replace("rsbweb.nih.gov/ij", "imagej.net");
		}
		return url;
	}
	
	private ImagePlus openCachedImage(String url) {
		if (url==null)
			return null;
		String ijDir = IJ.getDirectory("imagej");
		if (ijDir==null)
			return null;
		int slash = url.lastIndexOf('/');
		File file = new File(ijDir + "samples", url.substring(slash+1));
		if (!file.exists())
			return null;
		if (url.endsWith(".gif"))  // ij.plugin.GIF_Reader does not correctly handle inverting LUTs
			return openJpegOrGif(file.getParent()+File.separator, file.getName());
		return IJ.openImage(file.getPath());
	}

	/** Used by open() and IJ.open() to open text URLs. */
	void openTextURL(String url) {
		if (url.endsWith(".pdf")||url.endsWith(".zip"))
			return;
		String text = IJ.openUrlAsString(url);
		if (text!=null && text.startsWith("




© 2015 - 2025 Weber Informatics LLC | Privacy Policy