Creating a PIL Image from a Memory Stream Provided by the C Library

I have a char pointer for png data provided by c library. How to create an image in python from this data in memory. The c function is as follows:

 char *getImage(int *imgSize); 

In Python, I got char * as follows:

 imSize = c_int() img = c_char_p() img = c_char_p(my_c_api.getImage(byref(imSize))) 

char* returned to the img variable, and the image size in bytes is returned to the imSize variable.

When executing the following python script:

 im = Image.frombuffer("RGBA", (400,400), img.value, 'raw', "RGBA", 0, 1) 

I get the error ValueError: buffer is not large enough . I suspect the img variable in a call frombuffer . What do I need to do with the img variable to correctly transfer image data to the frombuffer call?

+4
source share
1 answer

You will need to put the data in an instance of StringIO , and PIL will StringIO data from this.

 from cStringIO import StringIO imgfile = StringIO(img.value) im = Image.open(imgfile) 

.frombuffer accepts raw image data, not PNG data. The StringIO object provides a file-like object for transferring your data, so PIL can work with it.

+4
source

All Articles