Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in Pythonista JPG Decoding #721

Open
jet082 opened this issue Nov 10, 2023 · 3 comments
Open

Bug in Pythonista JPG Decoding #721

jet082 opened this issue Nov 10, 2023 · 3 comments

Comments

@jet082
Copy link

jet082 commented Nov 10, 2023

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')
@cvpe
Copy link

cvpe commented Nov 24, 2023

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')

@cclauss
Copy link
Contributor

cclauss commented Nov 24, 2023

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

@cvpe
Copy link

cvpe commented Nov 24, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants