0

Use win8 and python3.4,I need to convert text to images.So I try to implement a himself.But I encounter a OSError.I try to use BytesIO instead of StringIO,it will pop error "OSError: cannot identify image file <_io.BytesIO object at xxxx>.

I still can't find the reason.

Codes as follow:

# -*- coding: utf-8 -*-
import os
import pygame
from io import StringIO,BytesIO
from PIL import Image

pygame.init()
text = u'This is a test text,test 123.'
font_path = "C:/windows/fonts/simsun.ttc"
im = Image.new("RGB",(300,50),(255,255,255))
font = pygame.font.Font(os.path.join(font_path),22)
rtext = font.render(text, True, (0,0,0),(255,255,255))

sio = StringIO()
print(sio.getvalue())
pygame.image.save(rtext, sio)
sio.seek(0)
#print(sio.getvalue())
line = Image.open(sio)
im.paste(line,(10,5))

im.show()
im.save("t1.png")

As is I get this error:

Traceback (most recent call last):
  File "D:/mypython/learn/demo.py", line 19, in <module>
    line = Image.open(sio)
  File "D:\Python34\lib\site-packages\PIL\Image.py", line 2319, in open
    % (filename if filename else fp))
OSError: cannot identify image file <_io.StringIO object at 0x00000000022810D8>
Moon
  • 1
  • 2

1 Answers1

0
line = Image.open(sio)

As far as I am concerned, sio is still a StringIO(). If you are trying to open it as an image, try opening it with line = Image.open(name), where name is the actual name of the image, not a StringIO().