Stream: helpdesk (published)

Topic: ✔ Package agnostic way to save a plot to disk?


view this post on Zulip Mason Protter (Apr 14 2022 at 23:32):

I have a function f(x) that receives some input that might be a plot or some form of image. If that's the case, I want to save that thing to a file, what's the right way to do this in a way that doesn't rely on me say, importing Plots.savefig?

E.g. I'm imagining something like

function f(x)
    if displayable("image/png", x)
        open(tempname(), "w+") do io
            print(io, "image/png", x) #this doesn't actually work as far as I can tell
        end
    else
        # something else
    end
end

view this post on Zulip Chad Scherrer (Apr 14 2022 at 23:34):

Have you tried FileIO.jl?
https://juliaio.github.io/FileIO.jl/stable/

view this post on Zulip Mason Protter (Apr 14 2022 at 23:34):

Wait a second, I just realized all I needed to do was use show instead of print :face_palm:

view this post on Zulip Mason Protter (Apr 14 2022 at 23:35):

Correct solution is

function f(x)
    if showable("image/png", x)
        open(tempname(), "w+") do io
            show(io, "image/png", x)
        end
    else
        # something else
    end
end

view this post on Zulip Notification Bot (Apr 14 2022 at 23:35):

Mason Protter has marked this topic as resolved.

view this post on Zulip Mason Protter (Apr 14 2022 at 23:35):

Chad Scherrer said:

Have you tried FileIO.jl?
https://juliaio.github.io/FileIO.jl/stable/

Thanks for the suggestion but I'm just doing absolute basics

view this post on Zulip Chad Scherrer (Apr 14 2022 at 23:35):

FileIO has this example:

function save(f::File{format"PNG"}, data)
    open(f, "w") do s
        # Don't forget to write the magic bytes!
        write(s, magic(format"PNG"))
        # Do the rest of the stuff needed to save in PNG format
    end
end

view this post on Zulip Mason Protter (Apr 14 2022 at 23:36):

Yeah, that's quite nice I'll keep it in mind

view this post on Zulip mbaz (Apr 15 2022 at 00:09):

Why do you use displayable instead of showable?

view this post on Zulip Mason Protter (Apr 15 2022 at 01:13):

I actually meant to write showable there, it was a typo in my MWE. Good eye!


Last updated: Nov 06 2024 at 04:40 UTC