从r socketConnection在浏览器中显示base64编码的图像

时间:2013-12-06 05:05:19

标签: r sockets base64

我在r中构建一个API,它从解析的URL返回一个特定的图像到浏览器。

目前,浏览器显示base64编码的字符串,而不是呈现图像。

这是一个可重复的例子:

    #### Reproducable Example for Stack-Overflow


library("plyr")
library("Cairo")
require("png")
library("base64enc")


# Always 'listening' server for returning image of mtcars dataset
Test_server <- function(){
  while(TRUE){
    writeLines("Listening...")
    CON <- socketConnection(host="localhost", port = 6011, blocking=TRUE, 
                            server=TRUE, open="r+")

    New_Request <- readLines(CON, 3)
    print(New_Request)

    Search <- strsplit(New_Request[1], split="/")[[1]][2]
    print(Search)

    IMG_Name <- paste0(Search, ".png")

    CairoPNG(IMG_Name, width=640, height=450)
    plot(mtcars[Search])
    IMG_TEST <- Cairo.capture()
#     dev.off()


    IMG_data <- dataURI(writePNG(IMG_TEST), mime="image/png")


    ### I have tried the following commands to print the IMAGE not the base64 to the browser:

#   SEND_img <- paste0("<img width='640' height='450' src='", IMG_data, "'></img>")
#   SEND_img <- paste0('<img src="', IMG_data, '"/>')
    SEND_img <- cat(sprintf("<img src=\"%s\" />", IMG_data), file=CON)
#   writeLines(SEND_img, CON)


    #Remember to close the connection! 
    close(CON)
  }
}


# Now run the server
Test_server()

运行服务器时,请转到

    http://127.0.0.1:6011/mpg/ 

    http:http://127.0.0.1:6011/disp/

浏览器会在pre标签中显示base64。 如何让所有(现代)浏览器显示此API中的图像?

谢谢!


编辑:新的工作代码如下:

# Always 'listening' server for returning image of mtcars dataset
Test_server <- function(){
  while(TRUE){
    writeLines("Listening...")
    CON <- socketConnection(host="localhost", port = 6011, blocking=TRUE, 
                            server=TRUE, open="a+b")


    New_Request <- readLines(CON, 3)
    print(New_Request)

    Search <- strsplit(New_Request[1], split="/")[[1]][2]
    print(Search)

    if (Search != "favicon.ico HTTP") {

      IMG_Name <- paste0(Search, ".png")

      CairoPNG(IMG_Name, width=640, height=450)
      plot(mtcars[Search])
      IMG_TEST <- Cairo.capture()
      dev.off()


      IMG_data <- dataURI(writePNG(IMG_TEST), mime="image/png")

      SEND_img <- cat(sprintf("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<img src=\"%s\" />", IMG_data), file=CON) 

    }
    #Remember to close the connection! 
    close(CON)
  }
}


# Now run the server
Test_server()

1 个答案:

答案 0 :(得分:1)

您需要HTTP标头,包括将内容类型设置为text / html的标头,否则浏览器不知道响应的内容。实际上,任何浏览器都会为没有标题的HTTP响应显示任何内容,这有点奇怪。

将SEND_img行替换为:

SEND_img <- cat(sprintf("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<img src=\"%s\" />", IMG_data), file=CON)