SkyWalker
SkyWalker

Reputation: 14309

How to add an in memory png image to a plot?

I have a png image that is generated automatically in memory as opposed to loading it from disk. I could of course save it first to disk but I'd rather not do it. I'd like to display that image somewhere in a ggplot2 plot but can't find the right package/function to do that.

The image I have in memory is e.g.

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

UPDATE a realistic use-case, and the error I get while trying to use Answer #1

library(qrencoder)
x <- qrencode_png("http://rud.is/b")
x
[1] "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAAAAACMfPpKAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAfElEQVQYlU2QWwrEMAwDR0vuf+XZj8qJSyjIyNYjAkAMQNFhkBCKzoNiin70kxKBN41ENuf7+9AZWQOGRx/2m4TeKy2YO0GyDpwszW5EUCs/ur78NZtGvSa8azdPDGttsonot8LtDFNnrs4yLSbuJk0ajnV3vevhCxUj4Q+R11n764g4WgAAAABJRU5ErkJggg=="
myImage <- png::readPNG(x)
  > Error in png::readPNG(x) : 
  > unable to open      
  > data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAAAAACMfPpKAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAfElEQVQYlU2QWwrEMAwDR0vuf+XZj8qJSyjIyNYjAkAMQNFhkBCKzoNiin70kxKBN41ENuf7+9AZWQOGRx/2m4TeKy2YO0GyDpwszW5EUCs/ur78NZtGvSa8azdPDGttsonot8LtDFNnrs4yLSbuJk0ajnV3vevhCxUj4Q+R11n764g4WgAAAABJRU5ErkJggg==

I have also tried the following but I get different errors:

qrGrob <- grid::gTree(children=gList(grid::rasterGrob(x)))

or

qrGrob <- grid::gTree(children=gList(grid::rasterGrob(x)))

Upvotes: 2

Views: 1398

Answers (3)

Grec001
Grec001

Reputation: 1121

Based on @SkyWalker , it works for me.

library(ggplot2)

library(raster)
library(qrencoder)
library(grid)



setwd("D:/WORK/R_Prj/OCR")
QRtxt <- paste0("Qt",round(runif(10)*10))

QR.in.Batch <- function(x){
qrGrob <- grid::rasterGrob(raster::as.raster(
  qrencoder::qrencode_raster(x), 
  maxpixels=.Machine$integer.max,col=c("white", "black")),
  interpolate=FALSE)    
ggplot() + geom_blank() + annotation_custom(qrGrob,0,1,0,1) 
}

lapply(QRtxt, QR.in.Batch)

Upvotes: 1

SkyWalker
SkyWalker

Reputation: 14309

I could not find any way to load the PNG from memory. However, this other way works perfectly using the raster version:

library(ggplot2)
library(raster)
library(qrencoder)
library(grid)
qrGrob <- grid::rasterGrob(raster::as.raster(
                 qrencoder::qrencode_raster("http://rud.is/b"), 
                 maxpixels=.Machine$integer.max,col=c("white", "black")),
                 interpolate=FALSE)    
ggplot() + geom_blank() + annotation_custom(qrGrob,0,1,0,1) 

Upvotes: 1

pogibas
pogibas

Reputation: 28329

This might work:

  • Read an image from a vector
  • Render an image
  • Plot using blank ggplot2 geom

Code:

myImage <- png::readPNG(x)
myImage <- grid::rasterGrob(myImage, interpolate = TRUE)
library(ggplot2)
ggplot() + 
    geom_blank() + 
    annotation_custom(myImage, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)

Upvotes: 5

Related Questions