Pythonista-Issues icon indicating copy to clipboard operation
Pythonista-Issues copied to clipboard

Bug in Pythonista JPG Decoding

Open jet082 opened this issue 2 years ago • 3 comments
trafficstars

The following code generates the error IOError: broken data stream when reading image file on the load line in Pythonista, but not PC.

import requests
from PIL import Image, ImageFile
from io import BytesIO
ImageFile.LOAD_TRUNCATED_IMAGES = False

url = "https://a.ltrbxd.com/resized/film-poster/3/6/9/9/8/36998-darling-0-1000-0-1500-crop.jpg"
response = requests.get(url)
image = Image.open(BytesIO(response.content))
image.load()

This code also fails if you use matplotlib to load the image instead of pillow.

You can get the code to run if you add ImageFile.LOAD_TRUNCATED_IMAGES = True, however, it only loads the image as a solid black image. As per the following code:

import requests
from PIL import Image, ImageFile
from io import BytesIO
ImageFile.LOAD_TRUNCATED_IMAGES = True

url = "https://a.ltrbxd.com/resized/film-poster/3/6/9/9/8/36998-darling-0-1000-0-1500-crop.jpg"
response = requests.get(url)
image = Image.open(BytesIO(response.content))
image.load()
image.save('out.png')

jet082 avatar Nov 10 '23 16:11 jet082

Please try this workaround

import ui

url = "https://a.ltrbxd.com/resized/film-poster/3/6/9/9/8/36998-darling-0-1000-0-1500-crop.jpg"
		
def load_image(): 
	iv.load_from_url(url)

iv = ui.ImageView()
iv.present()

# to understand why to use a delay, see topic (from 2015) 
# https://forum-new.omz-software.com/topic/1639/imageview-load_from_url-freezes-app
ui.delay(load_image,0.0)

# if you want a PIL image, you can still convert ui.Image to PIL
from PIL import Image
from io import BytesIO

def ui2pil(ui_img):
	png_data = ui_img.to_png()
	return Image.open(BytesIO(png_data))
	
pil_image = ui2pil(iv.image)
pil_image.save('out.png')

cvpe avatar Nov 24 '23 08:11 cvpe

Caution: BytesIO(png_data) allocates memory but never closes (frees) that memory. If you process many images, this may cause Pythonista to crash.

cclauss avatar Nov 24 '23 10:11 cclauss

Caution: BytesIO(png_data) allocates memory but never closes (frees) that memory. If you process many images, this may cause Pythonista to crash.

Thanks, forgotten, some neurons were removed by my operation 😢 But not sure that somebody else would read my comment

cvpe avatar Nov 24 '23 11:11 cvpe