Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert R image to Base 64

Tags:

r

image

base64

I want to see find the base64 encoding of an image, so I can save a plot as part of a JSON file or embedded into an HTML page.

library(party)
irisct <- ctree(Species ~ ., data = iris)
plot(irisct, type="simple")

Are there other ways to share an R image over the web?

like image 717
jbest Avatar asked Oct 29 '15 08:10

jbest


2 Answers

If you have the package base64enc installed, it's much simpler, with equivalent results (assuming you have the image file.png already on disk):

# Using RCurl:
txt1 <- RCurl::base64Encode(readBin("file.png", "raw", file.info("file.png")[1, "size"]), "txt")

# Using base64encode:
txt2 <- base64enc::base64encode("file.png")

html1 <- sprintf('<html><body><img src="data:image/png;base64,%s"></body></html>', txt1)
html2 <- sprintf('<html><body><img src="data:image/png;base64,%s"></body></html>', txt2)
# This returns TRUE:
identical(html1, html2)

But using knitr::image_uri("file.png") (see Bert Neef's answer) is even simpler!

like image 193
sgrubsmyon Avatar answered Sep 21 '22 14:09

sgrubsmyon


You could try using knitr

library(knitr)

printImageURI<-function(file){
  uri=image_uri(file)
  file.remove(file)
  cat(sprintf("<img src=\"%s\" />\n", uri))    
}

the printImageURI function takes the filename of a file on disk (I use it quite often with PNG files generated by ggplot). It works great with Firefox, Chrome and IE.

like image 39
Bert Neef Avatar answered Sep 22 '22 14:09

Bert Neef