通过管道工服务任意图像文件

Oga*_*anM 2 r 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)
}
Run Code Online (Sandbox Code Playgroud)

并运行

plum = plumber::plumb('testPlumb.R')
plum$run(port=8000)
Run Code Online (Sandbox Code Playgroud)

如果您访问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
}
Run Code Online (Sandbox Code Playgroud)

代替code that'll help me serve the file上面的内容,我已经include_file按照这里的建议尝试了,但是失败了。

由于该code that modifies that file a little that doesn't matter here部分使用的是magick包,因此我也尝试使用来服务magick对象,print但也没有成功。

例如

#* @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
}
Run Code Online (Sandbox Code Playgroud)

结果是 {"error":["500 - Internal server error"],"message":["Error in file(data$file, \"rb\"): cannot open the connection\n"]}

Oga*_*anM 6

如此处所述需要绕过默认的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)
}
Run Code Online (Sandbox Code Playgroud)