How to display an image from the web in a QMainWindow

1

I would like to know how I can show an image brought from a url destro del qmainwindow.

this is the code:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import uic 
from PyQt5.Qt import *
import cv2
import urllib.request
import numpy as np
from urllib.request import *
from PIL import Image




class Principal(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        uic.loadUi("gif.ui",self)

        self.table.setColumnWidth(0,200)
        print(self.table.item(1,1).text())

        url = 'http://www.chis.mx/boletincanaco/wp-content/uploads/2012/07/Logo-Steren-Vertical-700x406.jpg'
        urlretrieve(url,'pic.jpg')

        img = Image.open('pic.jpg')
        img.show()



app = QApplication([])
p = Principal()
p.show()
app.exec_()

But it shows me the image using the windows viewer by default, and it does not show it destro of the qmain window

This is another file that tries to do the same but shows nothing.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import uic 
from PyQt5.Qt import *
import cv2
import urllib.request
import numpy as np




class Principal(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        uic.loadUi("gif.ui",self)

        self.table.setColumnWidth(0,200)
        print(self.table.item(1,1).text())
        self.url_to_image('http://www.chis.mx/boletincanaco/wp-content/uploads/2012/07/Logo-Steren-Vertical-700x406.jpg')

    def url_to_image(sel,url):
        resp = urllib.request.urlopen(url)
        image = np.asarray(bytearray(resp.read()),dtype="uint8")
        image = cv2.imdecode(image,cv2.IMREAD_COLOR)
        print(image)
        return image



app = QApplication([])
p = Principal()
p.show()
app.exec_()
    
asked by Revsky01 16.07.2018 в 06:41
source

1 answer

1

You should not use urllib because it is blocking, you should run it in a thread, but instead you can use QNetworkAccessManager that allows you to send requests and receive responses from the network.

On the other hand to show an image you can use QLabel.

from PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
        self.setCentralWidget(self.label)

        url = 'http://www.chis.mx/boletincanaco/wp-content/uploads/2012/07/Logo-Steren-Vertical-700x406.jpg'
        manager = QtNetwork.QNetworkAccessManager(self)
        manager.finished.connect(self.onFinished)
        manager.get(QtNetwork.QNetworkRequest(QtCore.QUrl(url)))

    @QtCore.pyqtSlot(QtNetwork.QNetworkReply)
    def onFinished(self, reply):
        image = QtGui.QImage.fromData(reply.readAll())
        if not image.isNull():
            self.label.setPixmap(QtGui.QPixmap.fromImage(image))
        reply.deleteLater()

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.showMaximized()
    sys.exit(app.exec_())

This method works if the url marks the image directly, storage services like drive, dropbox, etc. do not show the direct url of the image even when you indicate that they share it.

For example in the case of Google Drive, you must right click on the image and select Get link to Share :

Obtaining a url with the following format:

https://drive.google.com/open?id=[IMAGE-ID]

where IMAGE-ID is the identifier of the image, to obtain the correct url use the following format:

https://drive.google.com/uc?export=download&id=[IMAGE-ID]

The following script does it directly:

from PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
        self.setCentralWidget(self.label)

        share_url = 'https://drive.google.com/open?id=1PakzAn-XPIT3TalZZmuo1wtmDomnnRaE'
        share_id = QtCore.QUrlQuery(QtCore.QUrl(share_url).query()).queryItemValue("id")

        manager = QtNetwork.QNetworkAccessManager(self)
        manager.finished.connect(self.onFinished)
        url = QtCore.QUrl("https://drive.google.com/uc")
        params = QtCore.QUrlQuery()
        params.addQueryItem("export", "download")
        params.addQueryItem("id", share_id)
        url.setQuery(params)
        req = QtNetwork.QNetworkRequest(url)
        req.setAttribute(QtNetwork.QNetworkRequest.FollowRedirectsAttribute, True)
        manager.get(req)

    @QtCore.pyqtSlot(QtNetwork.QNetworkReply)
    def onFinished(self, reply):
        image = QtGui.QImage.fromData(reply.readAll())
        if not image.isNull():
            self.label.setPixmap(QtGui.QPixmap.fromImage(image))

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.showMaximized()
    sys.exit(app.exec_())

    
answered by 16.07.2018 / 08:47
source