Encode a plot to base64?

Hello everyone, I’m trying to encode a plot to base64 string, but facing some trouble.

That’s what I’m trying to do:

using Plotly

a = plot(x,y,title="Two Lines",label=["Line 1" "Line 2"],lw=3);
io = IOBuffer();
iob64_encode = Base64EncodePipe(io);
show(io, MIME"image/svg+xml", a);

And got the following error:

ERROR: MethodError: no method matching show(::Base.GenericIOBuffer{Array{UInt8,1}}, ::Type{MIME{Symbol("image/svg+xml")}}, ::Plots.Plot{Plots.GRBackend})
Closest candidates are:
  show(::IO, ::MIME{Symbol("text/plain")}, ::Plots.Plot) at C:\Users\Losses\.juliapro\JuliaPro_v1.1.1.1\packages\Plots\FQOz1\src\output.jl:194
  show(::IO, ::MIME{Symbol("text/plain")}, ::Any) at sysimg.jl:219
  show(::IO, ::DataType) at show.jl:436
  ...
Stacktrace:
 [1] top-level scope at none:0

It seems base64 encoder could only encode text? so which function should I use to get base64 of a image in most formats?

Firstly, show(io, MIME"image/svg+xml", a) should be written as show(io, MIME("image/svg+xml"), a) but I think Plotly only prints out to HTML (so something like sprint(show, MIME("text/html"), a)), based on https://github.com/sglyon/PlotlyJS.jl/blob/460b35b3507f1ce5c001354d0d2d03859ca60c70/src/display.jl#L16.

Thank you! I finally made something work!

The working code is:

using Plots, Base64;
x = 1:10; y = rand(10);
a = plot(x,y,title="Two Lines",label=["Line 1" "Line 2"],lw=3);
io = IOBuffer();
iob64_encode = Base64EncodePipe(io);
show(iob64_encode, MIME("image/svg+xml"), a);
close(iob64_encode);
str = String(take!(io));

MIME("image/svg+xml") will also work, I’ll continue my work on implementing another Shiny on Julia :smiley:

1 Like

There are already some efforts underway to do this. I don’t say this to discourage you from doing it yourself - having shiny in julia will be awesome and more power to anyone interested in taking that on - just wondering if it’s worth joining forces rather than duplicating effort. I suspect it’s a monumental task.

1 Like

I know that, but my main purpose is to learn something very basic about meta programming with Julia but not making something could be used on production environment :grinning:

2 Likes

Great! Carry on then :slight_smile: