Programmatically set display "zoom-level" in ImageJ/Fiji

Hi all, I am looking for a way to set the so-called “display magnification” or zoom-level for images in ImageJ/Fiji.
The ImageCanvas class has the setMagnification method, which indeed resize the canvas but the window size stays the same, and I could not find a simple equivalent for ImageWindows.

Below a jython snippet that set the Canvas magnification to 25%.

#@ImagePlus imp
canvas = imp.getCanvas()
canvas.setMagnification(0.25)
imp.updateAndDraw() 

Not perfectly sure what you try to obtain, but did you consider the Zoom-class?

I am trying to achieve basically this command of the menu Image > Zoom > Set… recorded by the macro-recorder as

IJ.run("Set... ", "zoom=50 x=800 y=600"); with a custom zoom value

but without using a IJ.run command, which I am afraid might break macro-recordability in my plugin (discussed in other threads).

I indeed checked the Zoom class, but there is no public method except the run (which is also not the IJ.run method).

Did you inspect the source code for Zoom?
Here it is a link:
https://imagej.nih.gov/ij/source/ij/plugin/Zoom.java

Yes I also checked it, but as you can see the code for setZoom is quite elaborated

Anyway, I came with an equivalent that works for most cases, although I was hoping for something more concise

#@ImagePlus imp
mag=0.5 # between 0 and 1
newWidth = int(imp.getWidth() * mag)
newHeight = int(imp.getHeight() * mag)

canvas = imp.getCanvas()
canvas.setMagnification(mag)

win = imp.getWindow()
win.setSize(newWidth, newHeight)

Sorry but I don’t understand.
If there is a solution, why not use it, be it elaborate or not?
You don’t need to code it, because it is given.

Personally, I prefer “Zoom >> To Selection” because it is a one-liner:

new Zoom().run( "to" );

You can always calculate the size of a selection that meets your needs for magnification – no?

As an alternative to the previous one, instead of resizing the canvas and then the window, one can resize the window and set the canvas to fit the window as following.

There is a slight difference between mag and the actual displayed zoom level, maybe due to the rounding error but otherwise it’s pretty nice.

#@ImagePlus imp
mag=0.25 # between 0 and 1
newWidth  = int(imp.getWidth() * mag)
newHeight = int(imp.getHeight() * mag)

win = imp.getWindow()
win.setSize(newWidth, newHeight)

canvas = imp.getCanvas()
canvas.fitToWindow()

Hi @LThomas,

The ImageJ 1.53i27 daily build adds these methods that are recorded by the Image>Zoom>To Selection and Image>Zoom>Set commands:

Zoom.toSelection(imp)
Zoom.set(imp,mag)
Zoom.set(imp,mag,x,y)
1 Like

Thanks Wayne,
that’s nice to have!

Thank you for always improving ImageJ Wayne, and for the rapid reaction !