如果我有一个已保存的图像文件,我该如何通过水管工为他们提供服务?
例如,这没有问题
# save this as testPlumb.R
library(magrittr)
library(ggplot2)
#* @get /test1
#* @png
test1 = function(){
p = data.frame(x=1,y= 1) %>% ggplot(aes(x=x,y=y)) + geom_point()
print(p)
}
并运行
plum = plumber::plumb('testPlumb.R')
plum$run(port=8000)
如果你转到http://localhost:8000/test1,你会看到正在投放的情节。
但我无法找到提供图像文件的方法
#* @get /test2
#* @png
test2 = function(){
p = data.frame(x=1,y= 1) %>% ggplot(aes(x=x,y=y)) + geom_point()
ggsave('file.png',p)
# code that modifies that file a little that doesn't matter here
# code that'll help me serve the file
}
代替上面的code that'll help me serve the file
,我按照建议here尝试include_file
,但失败了。
由于code that modifies that file a little that doesn't matter here
部分正在使用magick包,我还尝试使用print
提供magick对象,但也没有成功。
例如
#* @get /test3
#* @png
test3 = function(){
p = data.frame(x=1,y= 1) %>% ggplot(aes(x=x,y=y)) + geom_point()
ggsave('file.png',p)
fig = image_read(file)
fig = image_trim(fig)
print(fig) # or just fig
}
结果为{"error":["500 - Internal server error"],"message":["Error in file(data$file, \"rb\"): cannot open the connection\n"]}
答案 0 :(得分:4)
如上所述here,我们需要绕过默认的png序列化程序才能使其正常工作。因此,将#* @png
替换为#* @serializer contentType list(type='image/png')
并在最后通过readBin
读取文件可以解决问题
#* @get /test2
#* @serializer contentType list(type='image/png')
test2 = function(){
p = data.frame(x=1,y= 1) %>% ggplot(aes(x=x,y=y)) + geom_point()
file = 'file.png'
ggsave(file,p)
readBin(file,'raw',n = file.info(file)$size)
}