Search code examples
rbase64png

How to convert a base64 string to a png file with R?


I have a png image encoded in a base64 string mybase64. How can I convert this base64 string to a png file ?

I've tried:

  conn <- file("xxx.png", open = "wb")
  base64enc::base64decode(what = mybase64, output = conn)
  close(conn)

But that does not produce a png file.


Solution

  • I've found a solution.

    My base64 string:

    mybase64 <- "data:image/png;base64,iVBORw0KGgoAAAANSU......"
    

    Then:

      raw <- base64enc::base64decode(what = substr(mybase64, 23, nchar(mybase64)))
      png::writePNG(png::readPNG(raw), "mypng.png")