2

I am using PySimpleGui. I want to have a local place holder image.jpg until the button is pressed to load in a URL based JPG.

From searching around, I see people saying to use the PIL import, however it's a bit unclear currently to me, how to achieve this with my requirements.

I also am using Cloudscraper as whenever I would make URL request I would get blocked with a 403 error.

Here is test code:

import PySimpleGUI as sg
from PIL import ImageTk, Image
from PySimpleGUI.PySimpleGUI import Column, HorizontalSeparator, In, VSeperator
from io import BytesIO
import io
import os
import cloudscraper

url = "https://cdnb.artstation.com/p/users/avatars/000/149/439/large/fe2b0699a4a2db62eb2814d44c81a0cf.jpg"
scrapper = cloudscraper.create_scraper(browser={'browser': 'firefox','platform': 'windows','mobile': False}).get(url).content
im = Image.open(scrapper)

print(im.format, im.size, im.mode)


imgViewer = [
    [sg.Image(Image.open(""), key="-ArtistAvatarIMG-")],
    [sg.Button("Get Cover Image", key="Clicky")]
]

layout = [
    [ 
        sg.Column(imgViewer)
    ],
]

window = sg.Window("Testing", layout)

def main():
    while True:
        event, values = window.read()
        if event == "EXIT" or event == sg.WIN_CLOSED:
            break
        if event == "Clicky":
            window['-ArtistAvatarIMG-'].Update(im)
    window.close()

if __name__ == "__main__":
    cDir = os.getcwd()
    main()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Andrea Mele
  • 53
  • 2
  • 7

1 Answers1

2

sg.Image only supports PNG and GIF formats and since the image is jpg you have to convert it to png and for this you can use PIL:

import io
import os

import PySimpleGUI as sg
from PySimpleGUI.PySimpleGUI import Column, HorizontalSeparator, In, VSeperator

from PIL import Image

import cloudscraper

url = "https://cdnb.artstation.com/p/users/avatars/000/149/439/large/fe2b0699a4a2db62eb2814d44c81a0cf.jpg"
jpg_data = (
    cloudscraper.create_scraper(
        browser={"browser": "firefox", "platform": "windows", "mobile": False}
    )
    .get(url)
    .content
)

pil_image = Image.open(io.BytesIO(jpg_data))
png_bio = io.BytesIO()
pil_image.save(png_bio, format="PNG")
png_data = png_bio.getvalue()

imgViewer = [
    [sg.Image(data=png_data, key="-ArtistAvatarIMG-")],
    [sg.Button("Get Cover Image", key="Clicky")],
]
# ...

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241