Pythonista-Issues
Pythonista-Issues copied to clipboard
Bug in Pythonista JPG Decoding
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')
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')
Caution: BytesIO(png_data) allocates memory but never closes (frees) that memory. If you process many images, this may cause Pythonista to crash.
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