Search code examples
javapluginsimagej

ImageJ, adding a scale bar to ImagePlus


I am trying to add a scale bar to ImagePlus but I can not. When I was using windows I used the following commands:

IJ.selectWindow("window_name");
IJ.run("Set Scale...", "distance=1 known="+pixelSize+" pixel=1 unit=um");
IJ.run("Scale Bar...", "width="+barSize+" height=3 font=12 color=Black location=[Upper Right]");

I hope someone can help me, I let the code to be seen:

String name = "example.jpg";
ImagePlus cRoiDuplicated = this.cROI.duplicate();
cRoiDuplicated.setTitle(name);

if (barSize != -1){
  [Code]
  /*IJ.run("Set Scale...", "distance=1 known="+pixelSize+" pixel=1 unit=um");
  IJ.run("Scale Bar...", "width="+barSize+" height=3 font=12 color=Black location=[Upper Right]");*/
}

FileSaver fs = new FileSaver(cRoiDuplicated);
fs.saveAsJpeg(this.directory + name);
cRoiDuplicated.close();

Solution

  • In a Java plugin, you should use the IJ.run(ImagePlus imp, String command, String options) method that takes an ImagePlus as first input argument.

    Use the Macro recorder in Java mode to get the required commands. The following plugin was created by

    • opening the recorder window (Plugins > Macros > Record...),
    • opening the 'Blobs' sample image (File > Open Samples > Blobs (25K)),
    • setting the scale (Analyze > Set Scale...),
    • adding the scale bar (Analyze > Tools > Scale Bar...), and then
    • clicking on the 'Create' button in the Recorder window.

    This is the generated code:

    import ij.*;
    import ij.process.*;
    import ij.gui.*;
    import java.awt.*;
    import ij.plugin.*;
    import ij.plugin.frame.*;
    
    public class My_Plugin implements PlugIn {
    
        public void run(String arg) {
            ImagePlus imp = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif");
            IJ.run(imp, "Set Scale...", "distance=1 known=2 pixel=1 unit=um");
            IJ.run(imp, "Scale Bar...", "width=50 height=3 font=12 color=Black background=None location=[Upper right]");
            imp.show();
        }
    
    }