Reputation: 19379
This code assigns a raster pixmap to a label. Instead of generating one I could simply read a local file:
img = QtGui.QImage('/Users/user/Desktop/photo.jpg')
I wonder if there is a way to specify the URL link instead of file path? Then QLabel
would get its pixmap straight from a web?
from PyQt4 import QtCore, QtGui
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
if not QtGui.QApplication.instance():
app=QtGui.QApplication([])
window = QtGui.QWidget()
window.setLayout(QtGui.QVBoxLayout())
img = QtGui.QImage(32, 32, QtGui.QImage.Format_RGB32)
img.fill(QtCore.Qt.red)
pixmap = QtGui.QPixmap(img)
lbl = QtGui.QLabel()
lbl.setPixmap(pixmap)
icon = QtGui.QIcon(pixmap)
window.layout().addWidget(lbl)
window.show()
sys.exit(app.exec_())
Upvotes: 3
Views: 4154
Reputation: 111
To my knowledge, there is no direct way of getting a QImage or QPixMap to load data straight from a URL. But you can bypass that by first extracting the data from the URL, and then loading it to a QPixMap.
Get data from the URL:
import urllib2
url_data = urllib2.urlopen(path).read()
Python3:
import urllib.request
url_data = urllib.request.urlopen(path).read()
Now load it to your QPixMap:
pixmap = QPixmap()
pixmap.loadFromData(url_data)
lbl.setPixmap(pixmap)
It is worth saying you should try and catch exceptions like urllib2.URLError
or InvalidURL
, handle cases where the URL is secured (https) etc.
Upvotes: 4
Reputation: 1
'''
import requests
''' imageurl = "your url here" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" }
try: with requests.get(image_url, headers=headers, stream=True) as response: response.raise_for_status()
# Read the content in chunks to handle large files
url_data = b""
for chunk in response.iter_content(chunk_size=8192):
url_data += chunk
'''
# Continue with your image processing code
image = QImage()
image.loadFromData(url_data)
image_label = QLabel()
image_label.setPixmap(QPixmap(image))
# image_label.setFixedSize() # Adjust the size as needed
layout.addWidget(image_label)
''' except requests.HTTPError as e: print(f"Failed to retrieve image. HTTP Error: {e}") except Exception as e: print(f"An error occurred: {e}") '''
Upvotes: 0