IOError: broken data stream when reading image file - python

This is the code(a simple python code which could add a number to a picture):
from PIL import Image, ImageDraw, ImageFont
def addnum(number, filepath):
img = Image.open(filepath)
width, height = img.size
draw = ImageDraw.Draw(img)
front_size = height/4
ttf_front = ImageFont.truetype('Arial.ttf', front_size)
draw.text((width - front_size, 0), number, (255, 0, 0), font = ttf_front)
del draw
img.save('wechat_addnum.jpg')
img.show()
if __name__ == '__main__':
addnum('4','wechat.jpg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/JourneyWoo/Python/python100/python001/python000.py", line 27, in <module>
addnum('4','wechat.jpg')
File "/Users/JourneyWoo/Python/python100/python001/python000.py", line 16, in addnum
draw = ImageDraw.Draw(img)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageDraw.py", line 299, in Draw
return ImageDraw(im, mode)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageDraw.py", line 60, in __init__
im.load()
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageFile.py", line 244, in load
raise_ioerror(err_code)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageFile.py", line 59, in raise_ioerror
raise IOError(message + " when reading image file")
IOError: broken data stream when reading image file
I don't know the real problem, and from the google and other questions from stackoverflow I cannot find the method which could solve this problem.
Thank you!!

This is a know issue. Try to update Pillow using pip install Pillow --upgrade

Related

Opening multiple fonts with PIL.ImageFont.truetype() causes OSError

I have some code that is supposed to open a font in multiple sizes:
from PIL import ImageFont
INTER_BOLD_48 = ImageFont.truetype("assets/Inter-Bold.ttf", 48)
INTER_BOLD_36 = ImageFont.truetype("assets/Inter-Bold.tff", 36)
INTER_BOLD_28 = ImageFont.truetype("assets/Inter-Bold.tff", 28)
# more fonts get opened below, but it never makes it there
However, this throws the error OSError: cannot open resource
Full error:
File "/home/lazza/PycharmProjects/YippyBot/tests.py", line 4, in <module>
INTER_BOLD_36 = ImageFont.truetype("assets/Inter-Bold.tff", 36)
File "/home/lazza/PycharmProjects/YippyBot/venv/lib/python3.10/site-packages/PIL/ImageFont.py", line 1008, in truetype
return freetype(font)
File "/home/lazza/PycharmProjects/YippyBot/venv/lib/python3.10/site-packages/PIL/ImageFont.py", line 1005, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "/home/lazza/PycharmProjects/YippyBot/venv/lib/python3.10/site-packages/PIL/ImageFont.py", line 255, in __init__
self.font = core.getfont(
OSError: cannot open resource
From the error I realised that the first font opening was running fine.
So I tried changing the font size in the argument to see if setting it to 36 was the problem:
from PIL import ImageFont
INTER_BOLD_48 = ImageFont.truetype("assets/Inter-Bold.ttf", 36)
INTER_BOLD_36 = ImageFont.truetype("assets/Inter-Bold.tff", 36)
INTER_BOLD_28 = ImageFont.truetype("assets/Inter-Bold.tff", 28)
But the error is exactly the same:
Traceback (most recent call last):
File "/home/lazza/PycharmProjects/YippyBot/tests.py", line 4, in <module>
INTER_BOLD_36 = ImageFont.truetype("assets/Inter-Bold.tff", 36)
File "/home/lazza/PycharmProjects/YippyBot/venv/lib/python3.10/site-packages/PIL/ImageFont.py", line 1008, in truetype
return freetype(font)
File "/home/lazza/PycharmProjects/YippyBot/venv/lib/python3.10/site-packages/PIL/ImageFont.py", line 1005, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "/home/lazza/PycharmProjects/YippyBot/venv/lib/python3.10/site-packages/PIL/ImageFont.py", line 255, in __init__
self.font = core.getfont(
OSError: cannot open resource
So I figured maybe opening the same font twice was causing the problem and so commented the first line out:
# INTER_BOLD_48 = ImageFont.truetype("assets/Inter-Bold.ttf", 48)
INTER_BOLD_36 = ImageFont.truetype("assets/Inter-Bold.tff", 36)
Same error. I also tried duplicating the .ttf files and giving each font a unique name, as well as giving the full path to the font.
I am on Linux, but I don't see why that would be a problem as I provide the path to the font.

OsError(err) in PIL Image library using Image.paste

I am doing a small script to paste an image into a black background to have same size images for a dataset. Here is the script:
for file in glob.glob(imagetteDir):
r = str(file)
image = Image.open(file)
img = np.zeros([100,100,3],dtype=np.uint8)
imageio.imwrite('black.tif', img)
black = Image.open('black.tif')
position = ((black.width - image.width), (black.height - image.height))
print(position)
Image.Image.paste(black,image,position)
dirr , name = r.split("imagette")
path1 = name.raplace("Hexagone_resized","Hexagone")
print(path1)
black.save(imagetteresizeDir+path1)
So Image.Image.paste() make the following error that i didnt find how to resolve:
Traceback (most recent call last):
File "C:\Users\user\Documents\Project\segmentation\Imagette creation\resizing.py", line 29, in <module>
Image.Image.paste(black,image)
File "C:\Users\user\Anaconda3\envs\tf_gpu\lib\site-packages\PIL\Image.py", line 1455, in paste
im.load()
File "C:\Users\user\Anaconda3\envs\tf_gpu\lib\site-packages\PIL\TiffImagePlugin.py", line 1070, in load
return self._load_libtiff()
File "C:\Users\user\Anaconda3\envs\tf_gpu\lib\site-packages\PIL\TiffImagePlugin.py", line 1182, in _load_libtiff
raise OSError(err)
OSError: -2
Have you any idea from where it might come?
Thanks in advance for your help

how to extract text from web gif file using python

I am trying to extract text from a gif image using the below code, it has worked for png format not working for gif.
import pytesseract
import io
import requests
from PIL import Image
url = requests.get('http://article.sapub.org/email/10.5923.j.aac.20190902.01.gif')
img = Image.open(io.BytesIO(url.content))
text = pytesseract.image_to_string(img)
print(text)
getting this error
C:\python\lib\site-packages\PIL\Image.py:1048: UserWarning: Couldn't allocate palette entry for transparency
warnings.warn("Couldn't allocate palette entry for transparency")
Traceback (most recent call last):
File "D:/elifesciences/prox.py", line 8, in <module>
text = pytesseract.image_to_string(img)
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 345, in image_to_string
}[output_type]()
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 344, in <lambda>
Output.STRING: lambda: run_and_get_output(*args),
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 242, in run_and_get_output
temp_name, input_filename = save_image(image)
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 173, in save_image
image.save(input_file_name, format=extension, **image.info)
File "C:\python\lib\site-packages\PIL\Image.py", line 2088, in save
save_handler(self, fp, filename)
File "C:\python\lib\site-packages\PIL\GifImagePlugin.py", line 507, in _save
_write_single_frame(im, fp, palette)
File "C:\python\lib\site-packages\PIL\GifImagePlugin.py", line 414, in _write_single_frame
_write_local_header(fp, im, (0, 0), flags)
File "C:\python\lib\site-packages\PIL\GifImagePlugin.py", line 532, in _write_local_header
transparency = int(transparency)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
Process finished with exit code 1
The idea is to convert each of the frames to RGB image before performing the OCR on them, as shown below -
for frame in range(0,img.n_frames):
img.seek(frame)
imgrgb = img.convert('RGBA')
imgrgb.show()
text = pytesseract.image_to_string(imgrgb)
print(text)
Working sample - https://colab.research.google.com/drive/1ctjk3hH0HUaWv0st6UpTY-oo9C9YCQdw

OSError: [Errno 9] Bad file descriptor while saving image with PIL

i amusing PIL to write some text inside and an image and then saving it at the same location. Following is my function which does this
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def add_text_to_image(image_path):
img = Image.open(image_path)
img = img.convert('RGB')
widht, height = img.size
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("helvetica.ttf", 20)
draw.text((0, 0), "Some text", (0, 0, 0), font=font)
img.save(image_path)
But i am getting following error.
Traceback (most recent call last): File
"/usr/local/lib/python3.6/site-packages/background_task/tasks.py",
line 43, in bg_runner func(*args, **kwargs) File
"/home/paksign/app/app/document/tasks.py", line 74, in
document_status_changed_to_completed
add_branding_texts_to_document_images(meta) File
"/home/paksign/app/app/document/utils.py", line 277, in
add_branding_texts_to_document_images for snapshot in snapshots: File
"/home/paksign/app/app/document/utils.py", line 270, in
add_text_to_image img.save(image_path) File
"/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 1994, in
save save_handler(self, fp, filename) File
"/usr/local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line
761, in _save ImageFile._save(im, fp, [("jpeg", (0, 0)+im.size, 0,
rawmode)], bufsize) File
"/usr/local/lib/python3.6/site-packages/PIL/ImageFile.py", line 519,
in _save s = e.encode_to_file(fh, bufsize) OSError: [Errno 9] Bad file
descriptor Marking task
document.tasks.document_status_changed_to_completed as failed
i have tried some solution from internet but nothing is working and i don't know what i am doing wrong here. any help is appreciated

AttributeError: load (scapy packet.py)

I've looked around and could not find anything regarding this. The issue is probably due to me being somewhat new to Python and I was hoping I could get some help here.
I came across this blog post from 2009: http://stacksmash.org/2009/09/packet-visualization-with-python/
However when I run this, I get the following error in line 1129 of Scapy's packet.py
$ python test-image.py
Traceback (most recent call last):
File "test-image.py", line 9, in <module>
if(len(pkt.load) > imgWidth):
File "/usr/local/lib/python2.7/dist-packages/scapy/packet.py", line
192, in __getattr__
fld,v = self.getfield_and_val(attr)
File "/usr/local/lib/python2.7/dist-packages/scapy/packet.py", line
189, in getfield_and_val
return self.payload.getfield_and_val(attr)
File "/usr/local/lib/python2.7/dist-packages/scapy/packet.py", line
189, in getfield_and_val
return self.payload.getfield_and_val(attr)
File "/usr/local/lib/python2.7/dist-packages/scapy/packet.py", line
1125, in getfield_and_val
raise AttributeError(attr)
AttributeError: load
Is this maybe an issue with newer library versions (considering this is a blogpost from 2009) or am I missing something here?
This works for me with Python 3.6.4:
from PIL import Image
from scapy.all import rdpcap
capture = rdpcap('./capture.pcap')
imgHeight = len(capture)
imgWidth = max(len(packet) for packet in capture)
imgSize = imgWidth, imgHeight
print('Image Size: ', imgSize)
img = Image.new('RGB', imgSize, (255, 255, 255))
for i in range(0, imgHeight):
for j in range(0, len(capture[i])):
color = ord(str(capture[i])[j])
# print('Writing pixel', (j,i), 'with value:', color)
img.im.putpixel((j,i), (0, color, 0))
img.save('./result.png')

Categories

Resources