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!