Search code examples
rr-rook-package

Add an image into an Rook web app using css


I have the following code which should produce a simple page with an image as background

r <- matrix(runif(9, 0, 1), 3)
g <- matrix(runif(9, 0, 1), 3)
b <- matrix(runif(9, 0, 1), 3)

col <- rgb(r, g, b)
dim(col) <- dim(r)

library(grid)
jpeg(filename="image.jpg")
grid.raster(col, interpolate=FALSE)
dev.off()

library(Rook)
server <- Rhttpd$new()

server$add(
  app=function(env){
    req <- Rook::Request$new(env)
    res <- Rook::Response$new()
    #....# r code
    res$write('
<!DOCTYPE html>
<html>
<head>              
<style>

body
{
background-image: url("image.jpg");
}

</style>
</head>
<body>
<h1>Hello World!</h1>
</h1>
</body>
</html>')

    res$finish()
  },
  name='webApp'
)

server$start(quiet=TRUE)
server$browse("webApp")

However, it doesn't show the image. I currently use a lot of css style formatting into the <head> tag but only background-image seems not to work... (just exporting everything inside the function res$write into a .html file and opening with browser does show the image)

EDIT:

NB: Relative or Absolute path does not make any difference unfortunately. Firebug and chrome dev tools both show the css line and no error is displayed. Can anyone of you see the image in the background running the example above?


Solution

  • Its an issue with paths. TLDR. add your working directory and give it a name (pic for example)

    Try the following:

    library(Rook)
    server <- Rhttpd$new()
    r <- matrix(runif(9, 0, 1), 3)
    g <- matrix(runif(9, 0, 1), 3)
    b <- matrix(runif(9, 0, 1), 3)
    
    col <- rgb(r, g, b)
    dim(col) <- dim(r)
    
    library(grid)
    jpeg(filename="image.jpg")
    grid.raster(col, interpolate=FALSE)
    dev.off()
    
    
    
    
    server$add(app = File$new(getwd()), name = 'pic')
    
    
    server$add(
      app=function(env){
        req <- Rook::Request$new(env)
        res <- Rook::Response$new()
        #....# r code
        res$write('
    <!DOCTYPE html>
    <html>
    <head>              
    <style>
    
    body
    {
    background-image: url("pic/image.jpg");
    }
    
    </style>
    </head>
    <body>
    <h1>Hello World!</h1>
    </h1>
    </body>
    </html>')
    
        res$finish()
      },
      name='webApp'
    )
    
    server$start(quiet=TRUE)
    server$browse("webApp")
    

    EDIT: Try working with the temporary directory:

    jpeg(filename=paste0(tempdir(), "/image.jpg"))
    

    and

    server$add(app = File$new(tempdir()), name = 'pic')