Python PyQt5.QtGui.QImage() Examples

The following are 30 code examples for showing how to use PyQt5.QtGui.QImage(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PyQt5.QtGui , or try the search function .

Example 1
Project: malss   Author: canard0328   File: waiting_animation.py    License: MIT License 6 votes vote down vote up
def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 200)))
        painter.setPen(QPen(Qt.NoPen))

        if self.lists is not None:
            path = os.path.abspath(os.path.dirname(__file__)) + '/static/'
            path += self.lists[self.list_index] + '.png'
            self.list_index += 1
            if self.list_index >= len(self.lists):
                self.list_index = 0
            image = QImage(path)
            rect_image = image.rect()
            rect_painter = event.rect()
            dx = (rect_painter.width() - rect_image.width()) / 2.0
            dy = (rect_painter.height() - rect_image.height()) / 2.0
            painter.drawImage(dx, dy, image)

        painter.end() 
Example 2
Project: Lector   Author: BasioMeusPuga   File: sorter.py    License: GNU General Public License v3.0 6 votes vote down vote up
def resize_image(cover_image_raw):
    if isinstance(cover_image_raw, QtGui.QImage):
        cover_image = cover_image_raw
    else:
        cover_image = QtGui.QImage()
        cover_image.loadFromData(cover_image_raw)

    # Resize image to what literally everyone
    # agrees is an acceptable cover size
    cover_image = cover_image.scaled(
        420, 600, QtCore.Qt.IgnoreAspectRatio)

    byte_array = QtCore.QByteArray()
    buffer = QtCore.QBuffer(byte_array)
    buffer.open(QtCore.QIODevice.WriteOnly)
    cover_image.save(buffer, 'jpg', 75)

    cover_image_final = io.BytesIO(byte_array)
    cover_image_final.seek(0)
    return cover_image_final.getvalue() 
Example 3
Project: Cura   Author: Ultimaker   File: PrintJobOutputModel.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, output_controller: "PrinterOutputController", key: str = "", name: str = "", parent = None) -> None:
        super().__init__(parent)
        self._output_controller = output_controller
        self._state = ""
        self._time_total = 0
        self._time_elapsed = 0
        self._name = name  # Human readable name
        self._key = key  # Unique identifier
        self._assigned_printer = None  # type: Optional[PrinterOutputModel]
        self._owner = ""  # Who started/owns the print job?

        self._configuration = None  # type: Optional[PrinterConfigurationModel]
        self._compatible_machine_families = []  # type: List[str]
        self._preview_image_id = 0

        self._preview_image = None  # type: Optional[QImage] 
Example 4
Project: Cura   Author: Ultimaker   File: NetworkMJPGImage.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self._stream_buffer = QByteArray()
        self._stream_buffer_start_index = -1
        self._network_manager = None  # type: QNetworkAccessManager
        self._image_request = None  # type: QNetworkRequest
        self._image_reply = None  # type: QNetworkReply
        self._image = QImage()
        self._image_rect = QRect()

        self._source_url = QUrl()
        self._started = False

        self._mirror = False

        self.setAntialiasing(True) 
Example 5
Project: Cura   Author: Ultimaker   File: PrintJobPreviewImageProvider.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def requestImage(self, id: str, size: QSize) -> Tuple[QImage, QSize]:
        """Request a new image.

        :param id: id of the requested image
        :param size: is not used defaults to QSize(15, 15)
        :return: an tuple containing the image and size
        """

        # The id will have an uuid and an increment separated by a slash. As we don't care about the value of the
        # increment, we need to strip that first.
        uuid = id[id.find("/") + 1:]
        for output_device in Application.getInstance().getOutputDeviceManager().getOutputDevices():
            if not hasattr(output_device, "printJobs"):
                continue

            for print_job in output_device.printJobs:
                if print_job.key == uuid:
                    if print_job.getPreviewImage():
                        return print_job.getPreviewImage(), QSize(15, 15)

                    return QImage(), QSize(15, 15)
        return QImage(), QSize(15, 15) 
Example 6
Project: Cura   Author: Ultimaker   File: ImageReader.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def preRead(self, file_name, *args, **kwargs):
        img = QImage(file_name)

        if img.isNull():
            Logger.log("e", "Image is corrupt.")
            return MeshReader.PreReadResult.failed

        width = img.width()
        depth = img.height()

        largest = max(width, depth)
        width = width / largest * self._ui.default_width
        depth = depth / largest * self._ui.default_depth

        self._ui.setWidthAndDepth(width, depth)
        self._ui.showConfigUI()
        self._ui.waitForUIToClose()

        if self._ui.getCancelled():
            return MeshReader.PreReadResult.cancelled
        return MeshReader.PreReadResult.accepted 
Example 7
Project: Writer-Tutorial   Author: goldsborough   File: part-3.py    License: MIT License 6 votes vote down vote up
def insertImage(self):

        # Get image file name
        filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Insert image',".","Images (*.png *.xpm *.jpg *.bmp *.gif)")

        if filename:
            
            # Create image object
            image = QtGui.QImage(filename)

            # Error if unloadable
            if image.isNull():

                popup = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical,
                                          "Image load error",
                                          "Could not load image file!",
                                          QtWidgets.QMessageBox.Ok,
                                          self)
                popup.show()

            else:

                cursor = self.text.textCursor()

                cursor.insertImage(image,filename) 
Example 8
Project: PyPipboyApp   Author: matzman666   File: localmapwidget.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _slotMapUpdate(self):
        #self.mapCoords.init( 
        #        self._mapUpdate.nw[0], self._mapUpdate.nw[1],
        #        self._mapUpdate.ne[0], self._mapUpdate.ne[1],
        #        self._mapUpdate.sw[0], self._mapUpdate.sw[1],
        #        self.mapItem.MAP_NWX, self.mapItem.MAP_NWY, 
        #        self.mapItem.MAP_NEX, self.mapItem.MAP_NEY, 
        #        self.mapItem.MAP_SWX, self.mapItem.MAP_SWY )
        image = QtGui.QImage(self._mapUpdate.pixels, self._mapUpdate.width, self._mapUpdate.height, QtGui.QImage.Format_Indexed8)
        image.setColorTable(self.COLORTABLE)
        self.playerMarker.setMapPos(self._mapUpdate.width/2, self._mapUpdate.height/2, self.playerMarker.mapPosR, False)
        if self.mapItem:
            self.mapItem._setMapPixmap(QtGui.QPixmap.fromImage(image))
        if self.mapEnabledFlag:
            self.playerMarker.setVisible(True)
        else:
            self.playerMarker.setVisible(False) 
Example 9
Project: GROOT   Author: ugroot   File: newsWindow.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self,parent="None",title="None",description="None",url="None",urlImage="None"):
        super(Tiles,self).__init__()
        #Heading Widget
        self.heading = QLabel('<b>%s</b>'%title)
        #SubHeading Widget with link to open in browser
        self.subHeading = QLabel('{}<a href="{}">...more</a>'.format(description,url))
        self.subHeading.setOpenExternalLinks(True)
        #Image Widget with article
        try:
            data = urllib.request.urlopen(urlImage).read()
        except:
            data = urllib.request.urlopen("https://ibb.co/XY30sjs").read()
        self.image = QImage()
        self.image.loadFromData(data)
        self.imageLabel = QLabel("image")
        self.imageLabel.setPixmap(QPixmap(self.image).scaled(64,64,Qt.KeepAspectRatio))
        self.tileLayout = QGridLayout()
        self.tileLayout.addWidget(self.heading,1,0)
        self.tileLayout.addWidget(self.imageLabel,1,1)
        self.tileLayout.addWidget(self.subHeading,2,0) 
Example 10
Project: Tools   Author: CharlesPikachu   File: genQrcode.py    License: MIT License 6 votes vote down vote up
def genQrcode(self):
		content = self.content_edit.text()
		try:
			margin = int(self.margin_spinbox.text())
		except:
			margin = 0
		size = int(self.size_combobox.currentText().split('*')[0])
		qr = qrcode.QRCode(version=1,
						   error_correction=qrcode.constants.ERROR_CORRECT_L,
						   box_size=size//29,
						   border=margin)
		qr.add_data(content)
		self.qr_img = qr.make_image()
		fp = io.BytesIO()
		self.qr_img.save(fp, 'BMP')
		qimg = QtGui.QImage()
		qimg.loadFromData(fp.getvalue(), 'BMP')
		qimg_pixmap = QtGui.QPixmap.fromImage(qimg)
		self.show_label.setPixmap(qimg_pixmap) 
Example 11
Project: pychemqt   Author: jjgomera   File: mainWindow.py    License: GNU General Public License v3.0 6 votes vote down vote up
def paintEvent(self, event):
        if self.count():
            QtWidgets.QTabWidget.paintEvent(self, event)
        else:
            painter = QtGui.QPainter(self)
            rect = event.rect()
            image = QtGui.QImage("images/pychemqt.png")
            rectImage = QtCore.QRect(25, rect.center().y()-50, 100, 100)
            painter.drawImage(rectImage, image)
            txt = QtWidgets.QApplication.translate(
                "pychemqt", """Welcome to pychemqt,
a software for simulating Chemical Engineering units operations,

Copyright © 2012 Juan José Gómez Romera (jjgomera)
Licenced with GPL.v3
This software is distributed in the hope that it will be useful,
but without any warranty, it is provided "as is" without warranty of any kind

You can start by creating a new project or opening an existing project.""",
                None)
            rect.setLeft(150)
            painter.drawText(rect, QtCore.Qt.AlignVCenter, txt) 
Example 12
Project: pychemqt   Author: jjgomera   File: mainWindow.py    License: GNU General Public License v3.0 6 votes vote down vote up
def savePFDImage(self):
        if self.filename[self.idTab]:
            dir = os.path.dirname(str(self.filename[self.idTab]))
        else:
            dir = "."
        fname = QtWidgets.QFileDialog.getSaveFileName(
            None,
            QtWidgets.QApplication.translate("pychemqt", "Save PFD as image"),
            dir, "Portable Network Graphics (*.png)")[0]
        if fname:
            rect = self.currentScene.sceneRect()
            img = QtGui.QImage(
                rect.width(), rect.height(),
                QtGui.QImage.Format_ARGB32_Premultiplied)
            p = QtGui.QPainter(img)
            self.currentScene.render(p)
            p.end()
            img.save(fname) 
Example 13
Project: Miyamoto   Author: aboood40091   File: spritelib.py    License: GNU General Public License v3.0 6 votes vote down vote up
def GetImg(imgname, image=False):
    """
    Returns the image path from the PNG filename imgname
    """
    imgname = str(imgname)

    # Try to find the best path
    path = 'miyamotodata/sprites/' + imgname

    for folder in reversed(SpritesFolders): # find the most recent copy
        tryPath = folder + '/' + imgname
        if os.path.isfile(tryPath):
            path = tryPath
            break

    # Return the appropriate object
    if os.path.isfile(path):
        if image: return QtGui.QImage(path)
        else: return QtGui.QPixmap(path) 
Example 14
Project: eddy   Author: danielepantaleone   File: view.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setGridSize(self, size):
        """
        Sets the grid size.
        """
        action = self.session.action('toggle_grid')
        size = clamp(size, 0)
        if size <= 0 or not action.isChecked():
            brush = QtGui.QBrush(QtCore.Qt.NoBrush)
        else:
            image = QtGui.QImage(size, size, QtGui.QImage.Format_RGB32)
            image.fill(QtCore.Qt.white)
            painter = QtGui.QPainter(image)
            painter.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor(80, 80, 80, 255)), 1, QtCore.Qt.SolidLine))
            painter.drawPoint(QtCore.QPointF(0, 0))
            painter.end()
            brush = QtGui.QBrush(image)
        self.setBackgroundBrush(brush) 
Example 15
Project: FeelUOwn   Author: feeluown   File: table.py    License: GNU General Public License v3.0 6 votes vote down vote up
def show_cover(self, cover, cover_uid, as_background=False):
        cover = Media(cover, MediaType.image)
        url = cover.url
        app = self._app
        content = await app.img_mgr.get(url, cover_uid)
        img = QImage()
        img.loadFromData(content)
        pixmap = QPixmap(img)
        if not pixmap.isNull():
            if as_background:
                self.meta_widget.set_cover_pixmap(None)
                self._app.ui.right_panel.show_background_image(pixmap)
            else:
                self._app.ui.right_panel.show_background_image(None)
                self.meta_widget.set_cover_pixmap(pixmap)
            self._app.ui.table_container.updateGeometry() 
Example 16
Project: vidpipe   Author: jchrisweaver   File: OpenCVQImage.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__( self, opencvBgrImg ):
#        depth = cv2.IPL_DEPTH_8U

        if len( opencvBgrImg.shape ) == 3:
            h, w, nChannels = opencvBgrImg.shape
            opencvRgbImg = np.zeros( ( h, w, 3 ), np.uint8 )
            opencvRgbImg = cv2.cvtColor( opencvBgrImg, cv2.COLOR_BGR2RGB )
        else:
#            img_format = QtGui.QImage.Format_Mono
            h, w = opencvBgrImg.shape
#            opencvRgbImg = np.zeros( ( h, w, 3 ), np.uint8 )
            opencvRgbImg = cv2.cvtColor( opencvBgrImg, cv2.COLOR_GRAY2RGB )
#            cv2.mixChannels( [ opencvBgrImg ], [ opencvRgbImg ], [ 0, 2 ] )

#        if depth != cv.IPL_DEPTH_8U or nChannels != 3:
#            raise ValueError("the input image must be 8-bit, 3-channel")

        self._imgData = opencvRgbImg.tostring()
        super( OpenCVQImage, self ).__init__( self._imgData, w, h, QtGui.QImage.Format_RGB888 ) 
Example 17
Project: PyQtImageViewer   Author: marcel-goldschen-ohm   File: QtImageViewer.py    License: MIT License 6 votes vote down vote up
def setImage(self, image):
        """ Set the scene's current image pixmap to the input QImage or QPixmap.
        Raises a RuntimeError if the input image has type other than QImage or QPixmap.
        :type image: QImage | QPixmap
        """
        if type(image) is QPixmap:
            pixmap = image
        elif type(image) is QImage:
            pixmap = QPixmap.fromImage(image)
        else:
            raise RuntimeError("ImageViewer.setImage: Argument must be a QImage or QPixmap.")
        if self.hasImage():
            self._pixmapHandle.setPixmap(pixmap)
        else:
            self._pixmapHandle = self.scene.addPixmap(pixmap)
        self.setSceneRect(QRectF(pixmap.rect()))  # Set scene size to image size.
        self.updateViewer() 
Example 18
Project: spimagine   Author: maweigert   File: gui_utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def arrayFromImage(fName):
    """converts png image to float32 array
    returns an array of shape [w,h,3]
    """
    try:
        img = QtGui.QImage(fName).convertToFormat(QtGui.QImage.Format_RGB32)


        Nx, Ny = img.width(),img.height()
        tmp = img.bits().asstring(img.numBytes())
        arr = np.frombuffer(tmp, np.uint8).reshape((Ny,Nx,4))
        arr = arr.astype(np.float32)/np.amax(arr)
        return arr[:,:,:-1][:,:,::-1]
    except Exception as e:
        print(e)
        print("could not load image %s"%fName)
        return np.zeros((10,100,3),np.float32) 
Example 19
Project: picasso   Author: jungmannlab   File: average3.py    License: MIT License 6 votes vote down vote up
def histtoImage(self, image):
        cmap = np.uint8(np.round(255 * plt.get_cmap("magma")(np.arange(256))))
        image /= image.max()
        image = np.minimum(image, 1.0)
        image = np.round(255 * image).astype("uint8")
        Y, X = image.shape
        self._bgra = np.zeros((Y, X, 4), dtype=np.uint8, order="C")
        self._bgra[..., 0] = cmap[:, 2][image]
        self._bgra[..., 1] = cmap[:, 1][image]
        self._bgra[..., 2] = cmap[:, 0][image]
        qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32)

        qimage = qimage.scaled(
            self.viewxy.width(),
            np.round(self.viewxy.height() * Y / X),
            QtCore.Qt.KeepAspectRatioByExpanding,
        )
        pixmap = QtGui.QPixmap.fromImage(qimage)

        return pixmap 
Example 20
Project: picasso   Author: jungmannlab   File: average3.py    License: MIT License 6 votes vote down vote up
def render_scene(
        self, autoscale=False, use_cache=False, cache=True, viewport=None
    ):
        kwargs = self.get_render_kwargs(viewport=viewport)
        n_channels = len(self.locs)
        if n_channels == 1:
            self.render_single_channel(
                kwargs, autoscale=autoscale, use_cache=use_cache, cache=cache
            )
        else:
            self.render_multi_channel(
                kwargs, autoscale=autoscale, use_cache=use_cache, cache=cache
            )
        self._bgra[:, :, 3].fill(255)
        Y, X = self._bgra.shape[:2]
        qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32)
        return qimage 
Example 21
Project: will-people-like-your-image   Author: cgtuebingen   File: gui.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def displayImg(self, frame):
        # w_width = self.frameGeometry().width()
        w_height = self.frameGeometry().height()

        height, width = frame.shape[:2]

        if height > w_height * 0.8:
            scale = w_height * 0.8 / float(height)
            frame = cv2.resize(frame, (0, 0), fx=scale, fy=scale)
            height, width = frame.shape[:2]

        # np.zeros((height, width, 3), dtype=np.uint8)
        data = np.array(frame[:, :, ::-1], dtype=np.uint8)
        q_img = QtGui.QImage(data, width, height, 3 *
                             width, QtGui.QImage.Format_RGB888)
        pixmap01 = QtGui.QPixmap.fromImage(q_img)
        self.image_preview.setPixmap(pixmap01)
        self.image_preview.setFixedWidth(width)
        self.image_preview.setFixedHeight(height) 
Example 22
Project: dcc   Author: amimo   File: BinViewMode.py    License: Apache License 2.0 5 votes vote down vote up
def cache(self):

        for i in [1, 2]:
            # pix = self._getNewPixmap(self.width, self.height)
            if not self.isInCache(self.dataModel.getPageOffset(i)):
                pix = QtGui.QImage(self.width, self.height, QtGui.QImage.Format_ARGB32)
                self.scrollPages(1, cachePix=pix, pageOffset=i)
                self.Paints[self.dataModel.getPageOffset(i)] = pix 
Example 23
Project: Lector   Author: BasioMeusPuga   File: pdf.py    License: GNU General Public License v3.0 5 votes vote down vote up
def render_pdf_page(page_data, for_cover=False):
    # Draw page contents on to a pixmap
    # and then return that pixmap

    # Render quality is set by the following
    zoom_matrix = fitz.Matrix(4, 4)
    if for_cover:
        zoom_matrix = fitz.Matrix(1, 1)

    pagePixmap = page_data.getPixmap(
        matrix=zoom_matrix,
        alpha=False)  # Sets background to White
    imageFormat = QtGui.QImage.Format_RGB888  # Set to Format_RGB888 if alpha
    pageQImage = QtGui.QImage(
        pagePixmap.samples,
        pagePixmap.width,
        pagePixmap.height,
        pagePixmap.stride,
        imageFormat)

    # The cover page doesn't require conversion into a Pixmap
    if for_cover:
        return pageQImage

    pixmap = QtGui.QPixmap()
    pixmap.convertFromImage(pageQImage)
    return pixmap 
Example 24
Project: Lector   Author: BasioMeusPuga   File: djvu.py    License: GNU General Public License v3.0 5 votes vote down vote up
def render_djvu_page(page, for_cover=False):
    # TODO
    # Figure out how to calculate image stride
    # and if it impacts row_alignment in the render
    # method below
    # bytes_per_line = 13200

    djvu_pixel_format = djvu.decode.PixelFormatRgbMask(
        0xFF0000, 0xFF00, 0xFF, bpp=32)
    djvu_pixel_format.rows_top_to_bottom = 1
    djvu_pixel_format.y_top_to_bottom = 0

    # ¯\_(ツ)_/¯
    mode = 0

    page_job = page.decode(wait=True)
    width, height = page_job.size
    rect = (0, 0, width, height)
    output = page_job.render(
        mode, rect, rect, djvu_pixel_format)
        # row_alignment=bytes_per_line)

    imageFormat = QtGui.QImage.Format_RGB32
    pageQImage = QtGui.QImage(output, width, height, imageFormat)

    # Format conversion not only keeps the damn thing from
    # segfaulting when converting from QImage to QPixmap,
    # but it also allows for the double page mode to keep
    # working properly. We like format conversion.
    pageQImage = pageQImage.convertToFormat(
        QtGui.QImage.Format_ARGB32_Premultiplied)

    if for_cover:
        return pageQImage

    pixmap = QtGui.QPixmap()
    pixmap.convertFromImage(pageQImage)

    return pixmap 
Example 25
Project: qiew   Author: mtivadar   File: BinViewMode.py    License: GNU General Public License v2.0 5 votes vote down vote up
def cache(self):

        for i in [1,2]:
            #pix = self._getNewPixmap(self.width, self.height)
            if not self.isInCache(self.dataModel.getPageOffset(i)):
                pix = QtGui.QImage(self.width, self.height, QtGui.QImage.Format_ARGB32)
                self.scrollPages(1, cachePix=pix, pageOffset=i)
                self.Paints[self.dataModel.getPageOffset(i)] = pix
                #print 'cache' 
Example 26
Project: CHATIMUSMAXIMUS   Author: benhoff   File: main_window.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_icon_dict():
    icon_path = path.join(path.dirname(__file__), 'resources', 'icons', '')
    filepaths = glob.glob(str(icon_path) + '*.png')
    filenames = [path.basename(f).split('.')[0] for f in filepaths]
    file_platform = zip(filepaths, filenames)

    icon_dict = {name: QtGui.QImage(path) for (path, name) in file_platform}
    return icon_dict 
Example 27
Project: Cura   Author: Ultimaker   File: PrintJobOutputModel.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def getPreviewImage(self) -> Optional[QImage]:
        return self._preview_image 
Example 28
Project: Cura   Author: Ultimaker   File: PrintJobOutputModel.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def updatePreviewImage(self, preview_image: Optional[QImage]) -> None:
        if self._preview_image != preview_image:
            self._preview_image = preview_image
            self.previewImageChanged.emit() 
Example 29
Project: Cura   Author: Ultimaker   File: UM3PrintJobOutputModel.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def updatePreviewImageData(self, data: bytes) -> None:
        image = QImage()
        image.loadFromData(data)
        self.updatePreviewImage(image) 
Example 30
Project: Writer-Tutorial   Author: goldsborough   File: part-4.py    License: MIT License 5 votes vote down vote up
def insertImage(self):

        # Get image file name
        #PYQT5 Returns a tuple in PyQt5
        filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Insert image',".","Images (*.png *.xpm *.jpg *.bmp *.gif)")[0]

        if filename:
            
            # Create image object
            image = QtGui.QImage(filename)

            # Error if unloadable
            if image.isNull():

                popup = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical,
                                          "Image load error",
                                          "Could not load image file!",
                                          QtWidgets.QMessageBox.Ok,
                                          self)
                popup.show()

            else:

                cursor = self.text.textCursor()

                cursor.insertImage(image,filename)