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!