将 R 图像转换为 Base 64
Convert R image to Base 64
我想看看找到图像的 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 的回答)更简单!
我想看看找到图像的 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 的回答)更简单!