簡體   English   中英

通過管道工服務任意圖像文件

[英]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 filecode that'll help me serve the file但失敗了。

由於對code that modifies that file a little that doesn't matter herecode 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM