'download an image as a temp file and setting it as pixmap
I'm downloading a YouTube video thumbnail and saving it as a tempfile. I'm then getting a pixmap out of that tempfile and later I can set it to a label, it will appear for the YouTube video thumbnail. My problem is that the same method won't work for YouTube #shorts thumbnail, it wont throw any error but the label will be empty. I dont know why
This is an example of a YouTube video thumbnail image url:
url = "https://i.ytimg.com/vi/MtN1YnoL46Q/hqdefault.jpg?sqp=-oaymwEjCOADEI4CSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDlF_ZTyfJ1i9Vw9HqEm5d5D5zL9Q"
This is an example of a YouTube shorts thumbnail image url:
url = "https://i.ytimg.com/vi/VT_7UBAf3Vc/2.jpg"
This is the code that works for the YouTube video thumbnails but not for the shorts
from PyQt5.QtGui import QIcon, QPixmap
from urllib.request import urlopen
import base64
import tempfile
url = .......
image = base64.b64encode(urlopen(url).read()).decode("ascii")
imgdata = base64.b64decode(image)
with tempfile.NamedTemporaryFile(mode="wb") as img:
img.write(imgdata)
pixmap = QPixmap(img.name)
How can I make it work for YouTube shorts image URLs too?
Solution 1:[1]
use the urllib.parse module to remove the parameters/args from the end of the url.
from PyQt5.QtGui import QIcon, QPixmap
from urllib.request import urlopen
from urllib.parse import urlparse, urlunparse # add parsing funcs
import base64
import tempfile
url = .......
url = urlunparse(list(urlparse(url)[:3]) + ['','','']) # try removing the arguments
image = base64.b64encode(urlopen(url).read()).decode("ascii")
imgdata = base64.b64decode(image)
with tempfile.NamedTemporaryFile(mode="wb") as img:
img.write(imgdata)
pixmap = QPixmap(img.name)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | alexpdev |