【发布时间】:2015-10-29 08:35:14
【问题描述】:
我想查看图片的 base64 编码,因此我可以将绘图保存为 JSON 文件的一部分或嵌入到 HTML 页面中。
library(party)
irisct <- ctree(Species ~ ., data = iris)
plot(irisct, type="simple")
还有其他方法可以在网络上共享 R 图像吗?
【问题讨论】:
我想查看图片的 base64 编码,因此我可以将绘图保存为 JSON 文件的一部分或嵌入到 HTML 页面中。
library(party)
irisct <- ctree(Species ~ ., data = iris)
plot(irisct, type="simple")
还有其他方法可以在网络上共享 R 图像吗?
【问题讨论】:
我不知道你想要完成什么,但这里有一个例子:
# 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)
【讨论】:
你可以试试 knitr
library(knitr)
printImageURI<-function(file){
uri=image_uri(file)
file.remove(file)
cat(sprintf("<img src=\"%s\" />\n", uri))
}
printImageURI 函数获取磁盘上文件的文件名(我经常将它用于 ggplot 生成的 PNG 文件)。它适用于 Firefox、Chrome 和 IE。
【讨论】:
如果您安装了包base64enc,它会简单得多,并且结果相同(假设您的磁盘上已经有图像file.png):
# 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)
但是使用knitr::image_uri("file.png")(参见 Bert Neef 的回答)更加简单!
【讨论】: