显示来自 URL 的图片

Display Image from URL

我正在尝试在 pyside6 中显示来自 URL 的图像,但无法正常工作。

def getIcon(data):
    iconID = data['weather'][0]['icon']
    icon = QPixmap("http://openweathermap.org/img/w/" + iconID + ".png");
    return icon

self.temperatureIcon = QtWidgets.QLabel(self).setPixmap(getIcon(self.weatherData))

是我的代码。

QPixmap 不会从 url 下载图像,因此您必须使用 QNetworkAccessManager 下载它:

import sys
from functools import cached_property

from PySide6.QtCore import Signal, QObject, Qt, QUrl
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PySide6.QtWidgets import (
    QApplication,
    QGridLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QWidget,
)


class ImageDownloader(QObject):
    finished = Signal(QImage)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.manager.finished.connect(self.handle_finished)

    @cached_property
    def manager(self):
        return QNetworkAccessManager()

    def start_download(self, url):
        self.manager.get(QNetworkRequest(url))

    def handle_finished(self, reply):
        if reply.error() != QNetworkReply.NoError:
            print("error: ", reply.errorString())
            return
        image = QImage()
        image.loadFromData(reply.readAll())
        self.finished.emit(image)


class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.lineedit = QLineEdit()
        self.button = QPushButton("Start")
        self.label = QLabel(alignment=Qt.AlignCenter)

        lay = QGridLayout(self)
        lay.addWidget(self.lineedit, 0, 0)
        lay.addWidget(self.button, 0, 1)
        lay.addWidget(self.label, 1, 0, 1, 2)

        self.downloader = ImageDownloader()

        self.downloader.finished.connect(self.handle_finished)
        self.button.clicked.connect(self.handle_clicked)

        self.lineedit.setText("http://openweathermap.org/img/wn/01d@2x.png")

        self.resize(640, 480)

    def handle_finished(self, image):
        pixmap = QPixmap.fromImage(image)
        self.label.setPixmap(pixmap)

    def handle_clicked(self):
        url = QUrl.fromUserInput(self.lineedit.text())
        self.downloader.start_download(url)


def main():
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

这里还有一个简单的solution\example:

import sys
import requests
from PySide6.QtGui     import QPixmap, QScreen
from PySide6.QtWidgets import QApplication, QWidget, QLabel


URL = 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_(test_image).png'


class App(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle('getAndSetImageFromURL()')
        self.label  = QLabel(self)
        self.pixmap = QPixmap()
        self.getAndSetImageFromURL(URL)
        self.resize(self.pixmap.width(),self.pixmap.height())
        screenSize = QScreen.availableGeometry(QApplication.primaryScreen())
        frmX = (screenSize.width () - self.width ())/2
        frmY = (screenSize.height() - self.height())/2
        self.move(frmX, frmY)
        self.show() 
    
    def getAndSetImageFromURL(self,imageURL):
        request = requests.get(imageURL)
        self.pixmap.loadFromData(request.content)
        self.label.setPixmap(self.pixmap)
        #QApplication.processEvents() # uncoment if executed on loop
    
      
if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = App()
    sys.exit(app.exec())
which outputs:
import sys
import requests

import PySide6
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PySide6.QtWidgets import QTableView, QWidget, QApplication, QGridLayout, QHeaderView
from PySide6.QtCore import Qt, QAbstractTableModel, QObject, Signal, QUrl
from PySide6.QtGui import QColor, QIcon, QPixmap, QImage

from datetime import datetime

    class MagicIcon():
        def __init__(self, link):
            self.link = link
            self.icon = QIcon()
            try:
                response = requests.get(self.link)
                pixmap = QPixmap()
                pixmap.loadFromData(response.content)
                self.icon = QIcon(pixmap)
            except:
                pass

    
    class MainWindow(QWidget):
        def __init__():
            super().__init__()
            self.setWindowIcon(MagicIcon(
                    "https://img.icons8.com/external-flatarticons-blue-flatarticons/65/000000/external-analysis-digital-marketing-flatarticons-blue-flatarticons-1.png"
            ).icon)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        wid = MainWindow()
        wid.show()
        sys.exit(app.exec())

使用requests模块获取图像并存储它们。