Adding an image to a datatable in R

前端 未结 1 1368
野的像风
野的像风 2021-01-18 03:42

I\'m trying to add an image to a datatable in R form the DT package. I fount this question: How to embed an image in a cell a table using DT, R and Shiny and it

相关标签:
1条回答
  • 2021-01-18 04:33

    This is one way to do it (by embedding base64 encoded images and using that for the src).

    First we'll make a small helper:

    img_uri <- function(x) { sprintf('<img src="%s"/>', knitr::image_uri(x)) }
    

    That will let us make a data uri. We're slurping up the whole file and converting it to base64 then doing a bit more formatting before sticking the entire blob into the src attribute.

    This is what a 1x1 pixel PNG looks like encoded that way:

    <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAAAXRSTlPM0jRW/QAAAApJREFUeJxjYgAAAAYAAzY3fKgAAAAASUVORK5CYII=\"/>
    

    So, we just do the same with the one you created:

    x = rnorm(1000)   
    png(paste0("test.png"))
    Plot = plot(x, type = "l")
    dev.off()
    
    camino = img_uri("test.png")
    data = data.frame(0.5 ,camino)
    DT::datatable(data, escape = FALSE)
    

    Yours is having an issue b/c it's not "URI" and it has no way of pulling from the local system. It might work in a browser context with a file://… URL.

    0 讨论(0)
提交回复
热议问题