Convert pyBarcode output to PIL image file

I am trying to convert pyBarcode output to a PIL image file without first saving the image. First, pyBarcode generates an image file, for example:

>>> import barcode >>> from barcode.writer import ImageWriter >>> ean = barcode.get_barcode('ean', '123456789102', writer=ImageWriter()) >>> filename = ean.save('ean13') >>> filename u'ean13.png' 

As you can see above, I do not want the image to be actually saved on my file system, because I want the result to be processed in the PIL image. So I made some changes:

 i = StringIO() ean = barcode.get_barcode('ean', '123456789102', writer=ImageWriter()) ean.write(i) 

Now I have a StringIO object, and I want the PIL to β€œread” it and convert it to a PIL image file. I wanted to use Image.new or Image.frombuffer , but both of these functions required me to enter a size ... can the size be determined from the StringIO data of the barcode? Image.open states this in its documentation:

You can use either a string (representing the file name) or a file object. In the latter case, the file object must implement the methods of reading, searching, and broadcasting and be opened in binary mode.

Is a StringIO instance a file object? How to open it as a binary file?

 Image.open(i, 'rb') >>> Image.open(i, 'rb') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/mark/.virtualenvs/barcode/local/lib/python2.7/site-packages/PIL/Image.py", line 1947, in open raise ValueError("bad mode") ValueError: bad mode 

I'm pretty close to the answer, I just need someone to be guided. Thanks in advance guys!

+7
source share
1 answer

StringIO objects are file objects.

However, if you use the cStringIO module (version of the C-optimized StringIO module), then note that after you finish the empty StringIO instance, it is write-optimized and you cannot use it as in the input file, and vice versa. Just repeat it in this case:

 i = StringIO(i.getvalue()) # create a cStringIO.StringO instance for a cStringIO.StringI instance. 

For the python version ( StringIO module) just try starting again:

 i.seek(0) 

You do not need to specify the file mode to call Image.open() ; if i not a string, it will be ignored anyway:

 img = Image.open(i) 
+7
source

All Articles