Example #1
0
    def start_drag(self):
        drag = QtGui.QDrag(self)
        mimeData = QtCore.QMimeData()
        ds = self.doc.data.get('0:kiln/Ts', False)
        if ds is False:
            ds = self.doc.data.get('0:kiln/T')
        T = ds.data[self.doc_idx]
        # Text copy
        mimeData.setData(
            "text/plain", 'point:{}:{}:{}'.format(self.base_dataset_path,
                                                  self.t, T))
        # Image copy
        ba = QtCore.QByteArray()
        buf = QtCore.QBuffer(ba)
        buf.open(QtCore.QIODevice.WriteOnly)
        self.img.save(buf, 'PNG')
        mimeData.setData("image/png", ba)
        ba1 = QtCore.QByteArray()
        buf1 = QtCore.QBuffer(ba1)
        buf1.open(QtCore.QIODevice.WriteOnly)
        self.img.save(buf1, 'BMP')
        mimeData.setData("image/bmp", ba1)
        # File copy
        name = '{}_{}.png'.format(
            self.base_dataset_path.replace('/', '_').replace(':', ''),
            self.idx)
        name = os.path.join(self.decoder.tmpdir, name)
        self.img.save(name, 'PNG')
        mimeData.setData("text/uri-list", "file:///" + name)

        mimeData.setImageData(self.img)
        drag.setMimeData(mimeData)
        drag.setPixmap(self.lbl_img.pixmap())
        logging.debug('start drag', mimeData.text())
        drag.exec_()
Example #2
0
    def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                "Unable to attach to shared memory segment.\nLoad an "
                "image first.")
            return

        buf = QtCore.QBuffer()
        ins = QtCore.QDataStream(buf)
        image = QtGui.QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QtCore.QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QtGui.QPixmap.fromImage(image))
    def drawBaseImage(self, backgroundImage, titleText, titleFont):

        if self._image == None or not self.lastBackgroundImage == backgroundImage:
            self.lastBackgroundImage = backgroundImage

            if backgroundImage == "":
                im = Image.new("RGB", (1280, 720), "black")
            else:
                im = Image.open(backgroundImage)

            # resize if necessary
            if not im.size == (1280, 720):
                im = im.resize((1280, 720), Image.ANTIALIAS)

            self._image = ImageQt(im)

        self._image1 = QtGui.QImage(self._image)
        painter = QPainter(self._image1)
        font = titleFont
        font.setPointSizeF(35)
        painter.setFont(font)
        painter.setPen(QColor(255, 255, 255))

        painter.drawText(70, 375, titleText)
        painter.end()

        buffer = QtCore.QBuffer()
        buffer.open(QtCore.QIODevice.ReadWrite)
        self._image1.save(buffer, "PNG")

        strio = io.BytesIO()
        strio.write(buffer.data())
        buffer.close()
        strio.seek(0)
        return Image.open(strio)
Example #4
0
    def capture(self, html_str):
        self.wb.mainFrame().setHtml(html_str)
        while not (self.saw_initial_layout and self.saw_document_complete):
            self.loop.processEvents()
            pass
        self.saw_initial_layout = False
        self.saw_document_complete = False
        # self.ready_trigger.connect(self.loop.exit)
        # self.loop.exec_()
        # while not self.wb.isModified():
        #     pass
        self.wb.setViewportSize(self.wb.mainFrame().contentsSize())
        img = QtGui.QImage(self.wb.viewportSize(), QtGui.QImage.Format_ARGB32)
        painter = QtGui.QPainter(img)
        self.wb.mainFrame().render(painter)
        painter.end()

        data = QtCore.QByteArray()
        buf = QtCore.QBuffer(data)
        img.save(buf, 'PNG')

        file_like = cStringIO.StringIO(data.data())
        pil_img = Image.open(file_like)
        tempfile_io = StringIO.StringIO()
        pil_img.save(tempfile_io, format='PNG')

        tb_image = ThebloqImage()
        tb_image.file = InMemoryUploadedFile(tempfile_io, None,
                                             'order_point_img.png',
                                             'image/png', tempfile_io.len,
                                             None)
        # tb_image.content_object = new_prod
        tb_image.save()
        # QtCore.QCoreApplication.instance().quit()
        return tb_image
Example #5
0
def svg2jpg(svgString):
    svgMatch = re.match(
        '.*viewBox.*viewBox=\"[ \t]*([0-9]+\.?[0-9]*)[ \t]+([0-9]+\.?[0-9]*)[ \t]+([0-9]+\.?[0-9]*)[ \t]+([0-9]+\.?[0-9]*)[ \t]*\".*$',
        svgString, re.DOTALL)
    if svgMatch:
        svgWidth = float(svgMatch.group(3))
        svgHeight = float(svgMatch.group(4))
    else:
        print 'makeSvgs: no match for width/height.'
        exit()

    #svgWidth = 200
    #svgHeight = 166
    #svgWidth = 100
    #svgHeight = 83

    #rect = QtCore.QRect(0,0,svgWidth,svgHeight)

    svgSize = QtCore.QSize(svgWidth, svgHeight)
    myXmlStreamReader = QtCore.QXmlStreamReader(svgString)
    myRenderer = QtSvg.QSvgRenderer(myXmlStreamReader)

    myImage = QtGui.QImage(svgSize, QtGui.QImage.Format_ARGB32)
    myTempPainter = QtGui.QPainter(myImage)
    myTempPainter.fillRect(myImage.rect(), QtCore.Qt.white)
    myRenderer.render(myTempPainter)
    myTempPainter.end()

    buf = QtCore.QBuffer()
    buf.open(QtCore.QIODevice.ReadWrite)
    myImage.save(buf, "JPG")

    buf.seek(0)
    jpg = buf.readAll()
    return jpg
    def mouseMoveEvent(self, event):
        """ If the mouse moves far enough when the left mouse button is held
            down, start a drag and drop operation.
        """
        if not event.buttons() & QtCore.Qt.LeftButton:
            return

        if (event.pos() - self.dragStartPosition).manhattanLength() \
             < QtGui.QApplication.startDragDistance():
            return

        if not self.hasImage:
            return

        drag = QtGui.QDrag(self)
        mimeData = QtCore.QMimeData()

        output = QtCore.QByteArray()
        outputBuffer = QtCore.QBuffer(output)
        outputBuffer.open(QtCore.QIODevice.WriteOnly)
        self.imageLabel.pixmap().toImage().save(outputBuffer, 'PNG')
        outputBuffer.close()
        mimeData.setData('image/png', output)

        drag.setMimeData(mimeData)
        drag.setPixmap(self.imageLabel.pixmap().scaled(64, 64, QtCore.Qt.KeepAspectRatio))
        drag.setHotSpot(QtCore.QPoint(drag.pixmap().width() / 2,
                                      drag.pixmap().height()))
        drag.start()
Example #7
0
 def wxfinished(self):
     if self.wxreply.error() != QNetworkReply.NoError:
         print "get radar error " + self.myname + ":" + str(
             self.wxreply.error())
         self.lastwx = 0
         return
     print "radar map received:" + self.myname + ":" + time.ctime()
     self.wxmovie.stop()
     self.wxdata = QtCore.QByteArray(self.wxreply.readAll())
     self.wxbuff = QtCore.QBuffer(self.wxdata)
     self.wxbuff.open(QtCore.QIODevice.ReadOnly)
     mov = QMovie(self.wxbuff, 'GIF')
     print "radar map frame count:" + self.myname + ":" + str(
         mov.frameCount())
     if mov.frameCount() > 2:
         self.lastwx = time.time()
     else:
         # radar image retreval failed
         self.lastwx = 0
         # retry in 5 seconds
         QtCore.QTimer.singleShot(5 * 1000, self.getwx)
         return
     self.wxmovie = mov
     self.wwx.setMovie(self.wxmovie)
     if self.parent().isVisible():
         self.wxmovie.start()
Example #8
0
    def getPhoto(self):
        bytes_ = QtCore.QByteArray()
        buffer_ = QtCore.QBuffer(bytes_)
        buffer_.open(QtCore.QIODevice.WriteOnly)
        self.labelPhoto.pixmap().save(buffer_, "PNG")

        return bytes_
Example #9
0
    def send_to_clients_evt(self):

        if len(self.connections) == 0:
            return

        # start = time.time()

        pix = QtGui.QImage(
            self.scene.width(),
            self.scene.height(),
            QtGui.QImage.Format_RGB888)
        painter = QtGui.QPainter(pix)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        self.scene.render(painter)
        painter.end()
        pix = pix.mirrored()

        block = QtCore.QByteArray()
        out = QtCore.QDataStream(block, QtCore.QIODevice.WriteOnly)
        out.setVersion(QtCore.QDataStream.Qt_4_0)
        out.writeUInt32(0)

        img = QtCore.QByteArray()
        buffer = QtCore.QBuffer(img)
        buffer.open(QtCore.QIODevice.WriteOnly)
        pix.save(buffer, "JPG", 95)
        out << img

        out.device().seek(0)
        out.writeUInt32(block.size() - 4)

        # print block.size()

        for con in self.connections:
            con.write(block)
Example #10
0
    def pasteImage(self,mimeData):
        # Code to insert mimedata image as base64
        if mimeData.hasImage():
            if str(mimeData.imageData().typeName()) == 'QImage':
                # Clipboard Paste
                img = QtGui.QImage(mimeData.imageData())
                ba = QtCore.QByteArray()
                buffer = QtCore.QBuffer(ba)
                buffer.open(QtCore.QIODevice.WriteOnly)
                img.save(buffer,'PNG')

                data = unicode(ba.toBase64())
            
            else:
                data= unicode(mimeData.imageData().toByteArray().toBase64())

        else:
            pth = unicode(mimeData.urls()[0].path())
            if os.name =='nt': pth = pth[1:]
            f = open(pth,'rb')
            data = base64.b64encode(f.read())
            f.close()
        try:
            ext = unicode(mimeData.urls()[0].path()).split('.')[-1].lower()
        except:
            ext='png'

        html = u'<img src="data:image/'+ext+';base64, '+data+'"><br />'
        self.insertText(html)

        self.page().mainFrame().evaluateJavaScript("CKEDITOR.instances.editor1.focus()")
        self.setFocus(1)
Example #11
0
	def onNetworkGetData(self, networkReply):
		# serve pages from our resource modules
		url = networkReply.url()
		if url.scheme() == 'file':
			fileInfo = QtCore.QFileInfo(url.path())
			name = str(fileInfo.baseName() )	#NOTE: we need to string it ..getattr() crasches otherwise
			ext = fileInfo.suffix()
			if ext == 'html':
				mimeType = 'text/html; charset=UTF-8'
				if name == 'About':
					data = self.aboutHtml()
				else:
					func = getattr(Tc2Config.HtmlPages, name, None)
					if func is None:
						data = '<h2>404: File Not Found</h2>'
					else:
						data = func()
				networkReply.setData(data, mimeType)
			elif ext == 'png':
				func = getattr(Tc2Config.Pixmaps, name, None)
				mimeType = 'image/png'
				if func is not None:
					arr = QtCore.QByteArray()
					p = QtCore.QBuffer(arr)
					p.open(p.WriteOnly)
					px = func()
					px.save(p, 'png')
					networkReply.setData(p.data(), mimeType)
			elif ext == 'css':
				func = getattr(Tc2Config.StyleSheets, name, None)
				mimeType = 'text/css'
				if func is not None:
					networkReply.setData(func(), mimeType)
Example #12
0
def convertPixmap(pixmap, brightness, contrast, saturation, sharpness):
    img = QtGui.QImage(pixmap)
    buffer = QtCore.QBuffer()
    buffer.open(QtCore.QIODevice.ReadWrite)
    img.save(buffer, "PNG")
    strio = cStringIO.StringIO()
    strio.write(buffer.data())
    buffer.close()
    strio.seek(0)
    im = Image.open(strio)
    im = ImageEnhance.Brightness(im).enhance(brightness)  #default 1
    im = ImageEnhance.Contrast(im).enhance(contrast)
    im = ImageEnhance.Sharpness(im).enhance(sharpness)
    im = im.filter(ImageFilter.UnsharpMask(radius=0, percent=100,
                                           threshold=0))  # default 0 100 0

    converter = ImageEnhance.Color(im)
    im = converter.enhance(saturation)
    #im1.save('/tmp/test.png')

    qt = ImageQt.ImageQt(im)
    imgout = QtGui.QImage(qt)
    rect = imgout.rect()
    #pixmapout=QtGui.QPixmap(imgout) #-> GARBLED IMAGES-----------------------v
    pixmapout = QtGui.QPixmap(
        imgout.copy(rect))  #Darn.. why. has to do with memory management?
    ################## This also worked: no garbled images when save/load was here:
    #tempfile='/tmp/TempCDEPanelResource'+str(self.tmpfilecounter)+'.png'
    #pixmapout.save(tempfile)
    #pixmapout=QtGui.QPixmap(tempfile)
    return pixmapout
Example #13
0
    def updateCachedImage(self):
        """Take the image from the Misura file, at the desired dataset and time"""
        s = self.settings
        if not os.path.exists(s.filename):
            self.updateCachedEmbedded()
            return
        from .. import filedata
        fp = filedata.getFileProxy(s.filename)
        t = s.target
        dec = self.dec
        dec.reset(fp, datapath=s.dataset)
        seq = dec.get_time(t)
        logging.debug('sequence', seq)
        r = dec.get_data(seq)
        fp.close()

        logging.debug('data', r)
        if not r:
            logging.debug('Could not get image data', t, seq)
            return
        t, pix = r
        ba = QtCore.QByteArray()
        buf = QtCore.QBuffer(ba)
        buf.open(QtCore.QIODevice.WriteOnly)
        pix.save(buf, 'PNG')
        encoded = veusz.compat.cbytes(ba.toBase64()).decode('ascii')
        logging.debug('encoded')
        self.cacheimage = pix
        self.cacheembeddata = encoded
Example #14
0
def byte_array_from(qimage):
    image_data = QtCore.QByteArray()
    buffer = QtCore.QBuffer(image_data)
    buffer.open(QtCore.QIODevice.WriteOnly)
    qimage.save(buffer, 'PNG')
    buffer.close()

    return image_data
Example #15
0
 def default_pixmap_as_bytes(self):
     xres = self.imgsize
     pixmap = icons.cola().pixmap(xres)
     byte_array = QtCore.QByteArray()
     buf = QtCore.QBuffer(byte_array)
     buf.open(QtCore.QIODevice.WriteOnly)
     pixmap.save(buf, 'PNG')
     buf.close()
     return byte_array
Example #16
0
    def fromQPixmap(klass, image):
        '''
		@param image: (QImage, QPixmap)
		'''
        arr = QtCore.QByteArray()
        p = QtCore.QBuffer(arr)
        p.open(p.WriteOnly)
        image.save(p, format='PGM')
        return klass(arr.data())
Example #17
0
    def sendMessage(self):
        buf = QtCore.QBuffer()
        buf.open(QtCore.QBuffer.ReadWrite)
        out = QtCore.QDataStream(buf)
        out.setVersion(QtCore.QDataStream.Qt_4_4)

        out << QtCore.QByteArray(json.dumps(self.hasRight))
        self.serverSocket.write(buf.data().data())
        self.serverSocket.flush()
Example #18
0
 def default_pixmap_as_bytes(self):
     xres = self.imgsize
     pixmap = QtGui.QPixmap(resources.icon('git.svg'))
     pixmap = pixmap.scaledToHeight(xres, Qt.SmoothTransformation)
     byte_array = QtCore.QByteArray()
     buf = QtCore.QBuffer(byte_array)
     buf.open(QtCore.QIODevice.WriteOnly)
     pixmap.save(buf, 'PNG')
     buf.close()
     return byte_array
Example #19
0
 def accept(self):
     settings = QtCore.QSettings()
     for name in self.fontsDict.keys():
         font = self.fontsDict.get(name).font()
         arr = QtCore.QByteArray()
         buf = QtCore.QBuffer(arr)
         buf.open(QtCore.QIODevice.WriteOnly)
         QtCore.QDataStream(buf) << font
         settings.setValue(name, arr)
     settings.sync()
     super(FontSettingsDialog, self).accept()
Example #20
0
    def __init__(self, filepath, parent=None):
        super().__init__(parent)
        self._fileName = ""

        data = b""
        with open(filepath, "rb") as file:
            self._fileName = file.name
            data = file.read()
        self._imageData = QtCore.QBuffer()
        self._imageData.setData(data)
        self.setDevice(self._imageData)
Example #21
0
	def incomingConnection(self, socketDescriptor):
		wBuffer = QtCore.QBuffer()
		self.threadID=str(len(self.threadList)+1)
		thread = ServerThread(socketDescriptor, wBuffer, self.threadID, self)
		self.bufferList.append(wBuffer)
		self.threadList.append(thread)
		if not self.parent.clientList.isEnabled():
			self.parent.clientList.setEnabled(True)
		self.parent.clientList.insertItem(int(self.threadID), QtCore.QString('Client '+self.threadID))
		self.parent.clientList.setItemData(int(self.threadID), QtCore.QVariant(self.threadID), 0)
		thread.start()
Example #22
0
 def setModelData(self, editor, model, index):
     ##print "setModelData", editor, model
     if isinstance(editor, _naf_imageviewer.cImageViewer):
         pixmap = editor.imageLabel.pixmap()
         bytes = QtCore.QByteArray()
         databuffer = QtCore.QBuffer(bytes)
         databuffer.open(QtCore.QIODevice.WriteOnly)
         pixmap.save(databuffer,
                     "PNG")  # writes pixmap into bytes in PNG format
         model.setData(index, QtCore.QVariant(bytes), QtCore.Qt.EditRole)
     else:
         super(cImageItemDelegate, self).setModelData(editor, model, index)
Example #23
0
    def icon2Blob(self, icon):
        """ Convert the thumbnail Icon to an Sqlite3 blob for insertion into DB

        Arguments:
            icon (QIcon)
        """
        if icon:
            pixmap = icon.pixmap(icon.availableSizes()[0])
            buff = QtCore.QBuffer()
            buff.open(QtCore.QIODevice.ReadWrite)
            pixmap.save(buff, 'png')
            return sqlite3.Binary(buff.data())
 def image2PIL(self):
     if self.image.isNull():
         return
     self.bufor = QtCore.QBuffer()
     self.bufor.open(QtCore.QIODevice.ReadWrite)
     self.image.save(self.bufor, "PNG")
     strio = cStringIO.StringIO()
     strio.write(self.bufor.data())
     self.bufor.close()
     strio.seek(0)
     self.pil_image = Image.open(strio)  #obraz w formacie PIL
     self.pil_image.save('pil_image.png', 'PNG')
Example #25
0
 def get_zip_graphic(self, name):
     if os.path.exists("ecu.zip"):
         zf = zipfile.ZipFile("ecu.zip", "r")
         zname = "graphics/" + name + ".gif"
         if not zname in zf.namelist():
             zname = "graphics/" + name + ".GIF"
         if zname in zf.namelist():
             ba = core.QByteArray(zf.read(zname))
             self.buffer = core.QBuffer()
             self.buffer.setData(ba)
             self.buffer.open(core.QIODevice.ReadOnly)
             self.img = gui.QMovie(self.buffer, 'GIF')
Example #26
0
    def paste_from_clipboard(self):
        """Paste an image from the clipboard into the editor"""
        mime_data = QtGui.QApplication.clipboard().mimeData()
        if mime_data.hasImage():
            byte_array = QtCore.QByteArray()
            buffer = QtCore.QBuffer(byte_array)
            image = QtGui.QImage(mime_data.imageData())
            image.save(buffer, 'PNG')

            def create_checkin(byte_array):
                return lambda: self.checkin_byte_array(byte_array, '.png')

            post(create_checkin(byte_array), self.stored_file_ready)
Example #27
0
    def loadFromFile(self):
        """ This slot function is called when the "Load Image From File..."
        button is pressed on the firs Dialog process.  First, it tests whether
        the process is already connected to a shared memory segment and, if so,
        detaches from that segment.  This ensures that we always start the
        example from the beginning if we run it multiple times with the same
        two Dialog processes.  After detaching from an existing shared memory
        segment, the user is prompted to select an image file.  The selected
        file is loaded into a QImage.  The QImage is displayed in the Dialog
        and streamed into a QBuffer with a QDataStream.  Next, it gets a new
        shared memory segment from the system big enough to hold the image data
        in the QBuffer, and it locks the segment to prevent the second Dialog
        process from accessing it.  Then it copies the image from the QBuffer
        into the shared memory segment.  Finally, it unlocks the shared memory
        segment so the second Dialog process can access it.  After self
        function runs, the user is expected to press the "Load Image from
        Shared Memory" button on the second Dialog process.
        """

        if self.sharedMemory.isAttached():
            self.detach()

        self.ui.label.setText("Select an image file")
        fileName = QtGui.QFileDialog.getOpenFileName(
            self, None, None, "Images (*.png *.xpm *.jpg)")
        image = QtGui.QImage()
        if not image.load(fileName):
            self.ui.label.setText(
                "Selected file is not an image, please select another.")
            return

        self.ui.label.setPixmap(QtGui.QPixmap.fromImage(image))

        # Load into shared memory.
        buf = QtCore.QBuffer()
        buf.open(QtCore.QBuffer.ReadWrite)
        out = QtCore.QDataStream(buf)
        out << image
        size = buf.size()

        if not self.sharedMemory.create(size):
            self.ui.label.setText("Unable to create shared memory segment.")
            return

        size = min(self.sharedMemory.size(), size)
        self.sharedMemory.lock()

        # Copy image data from buf into shared memory area.
        self.sharedMemory.data()[:] = buf.data().data()
        self.sharedMemory.unlock()
    def grabar(self):
        regMarker = self.liEjemplos[0].bloqueDatos
        nombre = regMarker.nombre.strip()
        if nombre == "":
            QTUtil2.mensError(self, _("Name missing"))
            return

        pm = self.liEjemplos[0].pixmapX()
        bf = QtCore.QBuffer()
        pm.save(bf, "PNG")
        regMarker.png = str(bf.buffer())

        self.regMarker = regMarker
        self.accept()
Example #29
0
    def handleButtonClassify(self):
        #self.scribbleArea.image.load('test.jpg')
        #self.scribbleArea.update()
        img = self.scribbleArea.image
        buffer = QtCore.QBuffer()
        buffer.open(QtCore.QIODevice.ReadWrite)
        img.save(buffer, "JPG")

        strio = cStringIO.StringIO()
        strio.write(buffer.data())
        buffer.close()
        strio.seek(0)
        pil_img = Image.open(strio)

        classifier(pil_img)
    def grabar(self):
        regFlecha = self.liEjemplos[0].bloqueDatos
        if self.siNombre:
            nombre = regFlecha.nombre.strip()
            if nombre == "":
                QTUtil2.mensError(self, _("Name missing"))
                return

        self.regFlecha = regFlecha

        pm = self.liEjemplos[0].pixmap()
        bf = QtCore.QBuffer()
        pm.save(bf, "PNG")
        self.regFlecha.png = str(bf.buffer())

        self.accept()