[英]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
}
我已按照此處的建議嘗試了include_file
來代替code that'll help me serve the file
的code that'll help me serve the file
但失敗了。
由於對code that modifies that file a little that doesn't matter here
的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"]}
如此處所述,需要繞過默認的png序列化程序才能完成此工作。 因此,將#* @png
替換為#* @serializer contentType list(type='image/png')
並最終通過readBin
讀取文件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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.