Convert R image to base 64

I want to see how to find the base64 encoding of an image so that I can save the graph as part of a JSON file or embedded in an HTML page.

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

Are there other ways to transfer R images over the Internet?

+11
r image base64
source share
3 answers

I donโ€™t know exactly what you want to accomplish, but here is an example:

 # save example plot to file png(tf1 <- tempfile(fileext = ".png")); plot(0); dev.off() # Base64-encode file library(RCurl) txt <- base64Encode(readBin(tf1, "raw", file.info(tf1)[1, "size"]), "txt") # Create inline image, save & open html file in browser html <- sprintf('<html><body><img src="data:image/png;base64,%s"></body></html>', txt) cat(html, file = tf2 <- tempfile(fileext = ".html")) browseURL(tf2) 

enter image description here

+12
source share

You can 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 accepts the name of a file on disk (I often use it with PNG files generated by ggplot). It works great with Firefox, Chrome, and IE.

+10
source share

If you have base64enc , it is much simpler, with equivalent results (if you already have the file.png image):

 # 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 easier!

+2
source share

All Articles