【问题标题】:How to convert a base64 string to a png file with R?如何使用 R 将 base64 字符串转换为 png 文件?
【发布时间】:2020-02-24 12:03:22
【问题描述】:

我有一个用 base64 字符串 mybase64 编码的 png 图像。如何将此 base64 字符串转换为 png 文件?

我试过了:

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

但这不会生成 png 文件。

【问题讨论】:

    标签: r base64 png


    【解决方案1】:

    我找到了解决办法。

    我的 base64 字符串:

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

    然后:

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

    【讨论】:

      【解决方案2】:

      应该这样做:)

      library(base64enc)
      
      inconn <- file("xxx.bin","rb")
      outconn <- file("xxx.png","wb")
      base64decode(what=inconn, output=outconn)
      close(inconn)
      close(outconn)
      

      【讨论】:

      • @StéphaneLaurent base64 应该写入本示例中的 xxx.bin
      • 好的,但是我有一个字符串。我应该怎么写到xxx.bin
      • @StéphaneLaurent 看看write to file in R。直接在代码中使用 base64 字符串会有点讨厌...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多