How to write a show function for an image-like type?

I’m developing a region module. A region is a subset of the discrete 2D cartesian plane. They can be used for very fast binary morphology and other things.

I’m trying to implement a show function, so that regions can be graphically displayed the same way as images can be displayed. My first attempt just creates an image (with binary content) and then shows the image.

using Images


"""
    Base.show(io, mime::MIME"image/png", r)

Shows a rich graphical display of a region. 
"""
function Base.show(io::IO, mime::MIME"image/png", r::Region)
    # convert region to an image and show image
    x0 = left(r)
    y0 = bottom(r)
    img = zeros(RGBA{N0f8}, height(r), width(r))
    for run in r.runs
        for column in run.columns
            img[run.row-y0+1, column-x0+1] = RGBA(0,0,1,0.5)
        end
    end
    Base.show(io, mime, img)
end

This forces me to use the Images module, which seems overkill to me. How could I write a show function with less severe dependencies on other modules?

I have been trying to find the source for the show function for images, but since I’m relatively new to Julia I was unable to find it.

Thanks and best regards
schrpe

@edit macro

In cases like this, you can use the @edit macro. All you do is add @edit in front of the command you are running, and Julia should open up the file housing the executed code.

In fact, if your editor supports jumping to a line number, Julia will even set your cursor to the exact line where the function definition is written.

caveat: You might have to to specify an editor using the ENV[] dictionnary if it isn’t already specified. For example:

ENV["EDITOR"]=raw"'C:\Program Files (x86)\Vim\vim81\gvim.exe'"

Your specific problem

For your specific problem, you can just add @edit in front of the call to Base.show():

@edit Base.show(io, mime, img)

On my version of Julia v1.6.1, @edit indicates that the code you are looking for is located in the ImageShow.jl package:

  • ImageShow/src/showmime.jl: line 23

So that should be a good starting point to figuring out how to serialize your data as a PNG without using ImageShow.jl.

My guess is you’ll probably need to write a bit of header data before you write out the image data.

You could try using a plot recipe for the Plots.jl package.