In R I create a raw vector containing a PNG image with the following test code.(format = ARGB (640 x 480))
library(Cairo)
library(png)
Cairo(type='raster')
x=seq(0,3,by=0.01)
y=2*sin(2*pi*(x-1/4))
plot(x,y) #Test plot
rawdata = writePNG(dev.capture(native=TRUE), raw())
assign("rawpng", rawdata, envir = .GlobalEnv)
The resulting vector looks like this:c(89, 50, 4e, 47, 0d, 0a, 1a, 0a, 00, 00, 00, 0d, 49, 48, 44,
52, 00, 00, 02, 80, 00, 00, 01, e0, 08, 06, 00, 00, 00, 35, d1,
dc, e4, 00, 00, 20, 00, 49, 44, 41, 54, 78, 9c, ec, dd, 77,
af, 5d, ee, cf, 75, 71,
41, d6, 90, 99, e7, ec, b3, 66, 9f, b5, d7, 7a, d6, b3, c0, cc,
cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc,
cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc, cc,.................................. b3, b0, fc, 1f, fe, 86, bd, ef, 71, 27, 9e, 88, 00, 00, 00, 00,
49, 45, 4e, 44, ae, 42, 60, 82)
Now i want to show the image in a Python canvas using the raw vector, but i can’t seem to get it right. Using Rpy2 and Pil, I somehow managed to generate an image, but it’s completly messed up.
rawdataVec = rpy2.robjects.globalenv['rawpng']
rawdataArray = numpy.asarray(rawdataVec)
newshape = (640,480,4)
newstrides = (rawdataArray.itemsize, rawdataArray.itemsize,rawdataArray.itemsize)
data = numpy.lib.stride_tricks.as_strided(rawdataArray, shape=newshape, strides=newstrides)
img = Image.fromstring('RGBA', (640,480), data.tostring(),'raw','RGBA',0,1)
photo = ImageTk.PhotoImage(image=img)
I know that saving the plot as an image file and reloading it in Python would be much easier, but I need it without saving the file first.
Is it even possible?
Could you write the image to a StringIO buffer (which essentially writes an image to a “file” in memory) and then read it in from that buffer?