通过水管工服务任意图像文件
Serve arbitrary image files through plumber
如果我有保存的图像文件,我如何通过管道工为他们提供服务?
例如,这没有问题
# 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
,我已经按照建议尝试了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"]}
如前所述here 需要绕过默认的 png 序列化器才能完成这项工作。所以用 #* @serializer contentType list(type='image/png')
替换 #* @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)
}
如果我有保存的图像文件,我如何通过管道工为他们提供服务?
例如,这没有问题
# 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
,我已经按照建议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"]}
如前所述here 需要绕过默认的 png 序列化器才能完成这项工作。所以用 #* @serializer contentType list(type='image/png')
替换 #* @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)
}