Skip to content

How to dump plots as bas64 strings?

5 messages · Patrick Meyer, Duncan Temple Lang, Gabor Grothendieck

#
Hello

My question might sound awkward, but I am looking for a way to somehow
convert a plot in R into a base64 string.

Here's an idea, but it is not at all satisfying.

1. write the plot to the harddisk:
---------------------------
png("toto.png")
plot(c(1,2,3))
dev.off()
---------------------------

2. somehow reload that file from the disk and transform it into a base64
string:
---------------------------
bin<-readBin(file("toto.png","rb"), raw(), n=1000,endian = "little")
...
---------------------------

Using the disk to perform this is not elegant, I don't know what value
to put for n, and I don't like the general idea.

Does anyone have a better suggestion? I have already searched on the
internet and in the mailing list, and I just found something on a
caTools package containing a base64encode & base64decode function.

Thanx for any ideas ...

Patrick
#
On Wed, Mar 4, 2009 at 9:17 AM, Patrick Meyer <paterijk at gmail.com> wrote:
This isn't much of an improvement and does not even address the main
concern but as no one has answered note that we can pass the filename
as a character string and it will get "rb" automatically and we can
just use "raw" if we like.  Also n can be any size larger than the file
size (see ?readBin) so if the file size is 10000 or less:

readBin("toto.png", "raw", n = 10000, endian = "little")
#
Here's the solution I'm using now, but it is not very "clean":

png("out.png")
plot(c(1,2,3))
dev.off()

system("base64 -w0 out.png > out.base64")
b64txt <- readLines(file("out.base64","rt"))

It would be nice to have an internal solution, even if this exactly does
what I want.

Patrick
Gabor Grothendieck wrote:
#
Patrick Meyer wrote:
I'm not certain which bit of this you are referring to when you say
"internal".  It would be covenient to have graphics devices be able to 
write to a buffer as well a  file and it wouldn't be terribly difficult
to do, but hasn't been a big enough problem so far.

As far calling the executable base64, why not use the function
in either the caTools or RCurl packages.

  D.
#
On Thu, Mar 5, 2009 at 1:27 PM, Duncan Temple Lang
<duncan at wald.ucdavis.edu> wrote:
I have faced this too, i.e. having to write out plots only
read them back in again, and if there are two of us I suspect there
are more facing thistoo.  I was using a different encoding but
that was not a problem in any case, just the annoyance of having
to write out files only to read them back in.