示例#1
0
 def __init__(self, parent, image_url, image_data, prompt_mode = False):
     super(ImageView,self).__init__(parent)
     self.accepted = False
     
     imgview = QtGui.QLabel(self)
 #    if '.gif' in image_url:
 #        movie = QtGui.QMovie(image_data)
 #        movie.start()
 #        imgview.setMovie(movie)
 #    else:
     pixmap = QPixmap()
     pixmap.loadFromData(image_data)
     imgview.setPixmap(pixmap)
     textbox_url = QtGui.QLineEdit(self)
     textbox_url.setText(image_url)
     textbox_url.setReadOnly(True)
     
     if prompt_mode:
         ok_button = QtGui.QPushButton('ADD', self)
         self.connect(ok_button, SIGNAL("clicked()"), self.OnAccept)
     
     hbox = QtGui.QHBoxLayout()
     hbox.addWidget(textbox_url)
     if prompt_mode:
         hbox.addWidget(ok_button)
     vbox = QtGui.QVBoxLayout(self)
     vbox.addWidget(imgview)
     vbox.addLayout(hbox)
     self.setLayout(vbox)
     self.show()
    def slide_next(self):

        indx = (self.start_indx * 9) + self.i + 1

        # Parse a URL into components
        url = urlparse.urlsplit(str(self.img_path_list1D[indx]))

        # Check if path is URL
        if url.scheme == "http" or url.scheme == "https":
            url = str(self.img_path_list1D[indx])
            data = urllib2.urlopen(url).read()
            pixmap = QPixmap()
            pixmap.loadFromData(data)

        else:
            pixmap = QPixmap(str(self.img_path_list1D[indx]))

        self.lbl_img.setPixmap(pixmap)
        self.i = self.i + 1

        # Control sliding buttons
        if indx > 0:
            self.btn_slidePrevious.setEnabled(True)

        if indx == (self.num_events - 1):
            self.btn_slideNext.setEnabled(False)
    def previous_gallery(self):

        self.start_indx = self.start_indx - 1

        # First clear previous
        for i in self.list_widget:
            i.clear()

        # Add new 9 images
        for i in range(0, 9):

            # Parse a URL into components
            url = urlparse.urlsplit(str(
                self.img_path_list[self.start_indx][i]))

            # Check if path is URL
            if url.scheme == "http" or url.scheme == "https":
                url = str(self.img_path_list[self.start_indx][i])
                data = urllib2.urlopen(url).read()
                pixmap = QPixmap()
                pixmap.loadFromData(data)
            else:
                pixmap = QPixmap(str(self.img_path_list[self.start_indx][i]))

            pixmap = pixmap.scaled(171, 151, Qt.IgnoreAspectRatio,
                                   Qt.SmoothTransformation)
            self.list_widget[i].setPixmap(pixmap)

        # Control sliding buttons
        if self.start_indx == 0:
            self.btn_previous.setEnabled(False)

        control = len(self.img_path_list1D) / 9
        if self.start_indx < (control - 1):
            self.btn_next.setEnabled(True)
示例#4
0
 def slotFinished(self):
     pixmap = QPixmap()
     pixmap.loadFromData(self.messageBuffer, self.frmt)
     if self.label:
         self.label.setPixmap(pixmap)
     if self.btn:
         self.btn.setIcon(QIcon(pixmap))
示例#5
0
文件: mainpanel.py 项目: buptlsp/coco
    def set_face_img(self, avatar):
        from PyQt4.QtGui import QPixmap

        pixmap = QPixmap()
        pixmap.loadFromData(avatar)
        self.avatar_base64 = avatar
        self.mw.avatar.setPixmap(pixmap)
示例#6
0
    def gps_update(self):
        if (self.gps_enable_u.isChecked()):
            self.gpsIndex+=self.gps_direction
            y = self.gps_points[self.gpsIndex].latitude
            x = self.gps_points[self.gpsIndex].longitude
            map_width=self.map_view_u.width()
            map_height=self.map_view_u.height()
            x1,y1=correct_gps(x,y)
            url='http://api.map.baidu.com/staticimage?center=%s,%s&width=%d&height=%d&zoom=14&markers=%s,%s' %(x1,y1,map_width,map_height,x1,y1)
            map_data = urllib.urlopen(url).read()
            baidu_map = QPixmap()
            baidu_map.loadFromData(map_data)

            self.map_view_u.setPixmap(baidu_map)
            self.map_view_u.show()
            
            if(self.gpsIndex == len(self.gps_points)):
                self.gps_direction=-1
            
            if (self.gpsIndex == 0):
                self.gps_direction=1
                
                          
            vins = self.getVIN()
            if (self.single_shot_enable_u.isChecked()):
                self.logger("Vechicle CNT=%d --> [GPS]: longtitude=%r latitude=%r "%(len(vins),x,y))
                self.logger(printStr2Hex(gps_assemble(str(vins[0]),x,y)),time_stamp=False)
                
            for vin in vins:
                packet = gps_assemble(str(vin),x,y)  
                if (self.soap_enable_button_u.isChecked()):
                    send_thread = send_packet_by_soap(self.soap,packet,"GPS")
                else:
                    send_thread = send_packet_by_kafka(self.producer,packet,"GPS")
                send_thread.start()
示例#7
0
 def set_verify_code(self, data):
     this = self.mw
     from PyQt4.QtGui import QPixmap
     pixmap = QPixmap()
     pixmap.loadFromData(data)
     this.login_vcimg.setPixmap(pixmap)
     this.login_vcimg.show()
示例#8
0
    def __previewReceived_(self, filename):
        """Received when a preview has been received
        
        @param filename: The filename of the preview
        @type filename: str
        """
        if config.DEBUG_GUI:
            print "<-- Preview received:", filename
        filename = str(filename)
        preview = self.__scanner_.previews[filename]
        del self.__scanner_.previews[filename]

        # Create the pixmap item
        pixmap = QPixmap()
        if preview == None:
            pixmap.load(config.NO_PREVIEW_FILENAME)
        else:
            pixmap.loadFromData(preview)
            
        # Add a black border
        self.__add_black_border_(pixmap)

        # Add the new icon to the list
        items = self.__basewidget_.imageList.findItems(filename, Qt.MatchExactly)
        items[0].setIcon(QIcon(pixmap))
示例#9
0
    def load(self):
        self.initTranslations()
        import vtk, VtkWidget, VtkWindow, Objects, Helpers
        self.vtk = vtk
        self.VtkWidget = VtkWidget
        self.VtkWindow = VtkWindow
        self.Objects = Objects
        self.Helpers = Helpers
        xpm = QPixmap()
        xpm.loadFromData(self.getFile('3dwin.xpm').read())
        winIcon = QIcon(xpm)
        self.winManager = SubWinManager(glb.mainWin.workSpace, self.VtkWindow.VtkWindow,
                QCoreApplication.translate('VtkWindow', "Vtk Window"), winIcon)
        testAction = QAction(winIcon,
            QCoreApplication.translate('VtkWindow', '&VtkWindow Test'), glb.mainWin)
        testAction.setStatusTip(QCoreApplication.translate('VtkWindow', 'Show a new Vtk test window'))
        QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
        glb.mainWin.plugInMenu.addAction(testAction)

        ftActions = glb.fileTypeActions
        ftActions.addType('application/x-3ds', '.3ds')
        ftActions.addAction(self.show3DS, ('application/x-3ds',),
            QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5)
        ftActions.addType('application/x-vrml', '.wrl')
        ftActions.addAction(self.showVRML, ('application/x-vrml',),
            QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5)

        return True
示例#10
0
 def set_file(self, file_path):
     self.clear()
     self.file_path = file_path
     if file_path and os.path.exists(file_path):
         pix_map = QPixmap()
         if file_path.endswith('.jpg'):
             jpg_data = read(file_path)
             str_io = StringIO.StringIO(jpg_data)
             img = Image.open(str_io)
             img.thumbnail((300,300), Image.ANTIALIAS)
             png_data = StringIO.StringIO()
             mode = img.mode
             if mode not in ('L', 'RGB'):
                 if mode == 'RGBA':
                     alpha = img.split()[3]
                     bg_mask = alpha.point(lambda x: 255 - x)
                     img = img.convert('RGB')
                     img.paste((255, 255, 255), None, bg_mask)
                 else:
                     img = img.convert('RGB')
             img.save(png_data, format='png')
             pix_map.loadFromData(QtCore.QByteArray(png_data.getvalue()))
         else:
             pix_map.load(file_path)
         self.addPixmap(pix_map)
示例#11
0
文件: login.py 项目: CoralResort/coco
 def set_verify_code(self, data):
     this = self.mw
     from PyQt4.QtGui import QPixmap
     pixmap = QPixmap()
     pixmap.loadFromData(data)
     this.login_vcimg.setPixmap(pixmap)
     this.login_vcimg.show()
示例#12
0
def getAssociatedImageUrl(source_url):
    print source_url

    # check if we can download an image directly via the source URL
    img = downloadImage(source_url)
    if img:
        return [source_url]

    ch = urlopen(source_url).read(1)
    if ch != '<':
        return []

    
    list_images_urls =[]
    # interpret the source URL as a html page
    soup1 = BeautifulSoup(urlopen(source_url).read())
    #print soup1('img')
    for img_tag in soup1('img'):
        if img_tag.parent.name == 'a':
            print " >> <img> inside <a>!"
            #print '>>>', img_tag.parent.name, img_tag.parent['href']
            # try to find <a> tag parenting the <img> and follow it
            if endsWithImageFileExtension(img_tag.parent['href']):
                list_images_urls.append(urljoin(source_url,img_tag.parent['href']))
                print " >> using the direct link to image in <a>"
            elif urlparse(img_tag.parent['href']).netloc == urlparse(source_url).netloc and urlparse(img_tag.parent['href']).path != '/':
                # got a link to the page in the same domain as source
                # go one level deeper
                print 'parent href', img_tag.parent['href'], urlparse(img_tag.parent['href']).path
                soup2 = BeautifulSoup(urlopen(urljoin(source_url,img_tag.parent['href'])).read())
                for img_tag2 in soup2('img'):
                    im2 = downloadImage(urljoin(source_url,img_tag2['src']))
                    if im2:
                        list_images_urls.append(urljoin(source_url,img_tag2['src']))
                        print " >> using the link to image in the OTHER page linked in <A>", img_tag2['src']
            else:
                im = downloadImage(urljoin(source_url,img_tag['src']))
                if im:
                    list_images_urls.append(urljoin(source_url,img_tag['src']))

    if len(list_images_urls) == 0:
        return []
    elif len(list_images_urls) > 1:
        list_images_urls_filtered =[]
        for img_url in list_images_urls:
            msgBox = QMessageBox()
            msgBox.setText(img_url)
            msgBox.setInformativeText("Press Save to store found image, press Cancel to reject it.")
            msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Cancel)
            msgBox.setDefaultButton(QMessageBox.Cancel)
            pix = QPixmap()
            pix.loadFromData(urlopen(img_url).read())
            msgBox.setIconPixmap(pix)
            if msgBox.exec_() == QMessageBox.Save:
                list_images_urls_filtered.append(img_url)
    
        return list_images_urls_filtered
    else:
        return list_images_urls
    def showFeatureDetail(self, errMsg, theFeature):
        strFeatureInfo = self.getFeatureInfoString(theFeature)
        self.textEditFeatureInfo.setText(strFeatureInfo)
        if self.mIsMyFeature(theFeature) == False:
            return

        errMsg = ['']
        pattern_dat, arrow_dat = self.getSpotguidePictures(
            errMsg, self.mTheLayer, theFeature)
        if errMsg[0] != '':
            #QMessageBox.information(self, "Show Spotguide", errMsg[0])
            return

        self.mPixmapList = []
        if pattern_dat is not None:
            patternDatParser = DatParser()
            patternDatParser.initFromMemory(errMsg,
                                            pattern_dat)  # pattern picture
            patternPixmap = QPixmap()
            patternPixmap.loadFromData(
                patternDatParser.getDatContentByIndex(errMsg, 0))
            self.mPixmapList.append(patternPixmap)

        if arrow_dat is not None:
            arrowDatParser = DatParser()
            arrowDatParser.initFromMemory(errMsg, arrow_dat)  # arrow picture
            arrowPixmap = QPixmap()
            arrowPixmap.loadFromData(
                arrowDatParser.getDatContentByIndex(errMsg, 0))
            if arrowDatParser.hasPointlist():
                # draw the point list on the arrow picture
                vecCoors = arrowDatParser.getPointListCoordinatesByIndex(
                    errMsg, arrowDatParser.getPointlistIndex())
                if errMsg[0] != '':
                    QMessageBox.information(self, "Show Spotguide", errMsg[0])
                    return
                with QPainter(arrowPixmap) as thePainter:
                    for oneXYPair in vecCoors:
                        thePainter.setPen(QPen(QColor(255, 0, 0)))
                        thePainter.drawPoint(oneXYPair[0], oneXYPair[1])
                        thePainter.drawPoint(oneXYPair[0] - 1, oneXYPair[1])
                        thePainter.drawPoint(oneXYPair[0] + 1, oneXYPair[1])
                        thePainter.drawPoint(oneXYPair[0], oneXYPair[1] - 1)
                        thePainter.drawPoint(oneXYPair[0], oneXYPair[1] + 1)

                # append pointlist information to the text box.
                strPointList = arrowDatParser.getPointListStringByIndex(
                    errMsg, arrowDatParser.getPointlistIndex())
                if errMsg[0] != '':
                    QMessageBox.information(self, "Show Spotguide", errMsg[0])
                    return
                strTemp = self.textEditFeatureInfo.toPlainText()
                strTemp += """\n\npointlist:\n"""
                strTemp += strPointList
                self.textEditFeatureInfo.setText(strTemp)
            self.mPixmapList.append(arrowPixmap)

        self.showImageInGraphicsView()
        return
示例#14
0
def get_Team_Pic(team):
    query = QSqlQuery("SELECT * FROM team WHERE name = '" + team + "'")
    query.next()
    picIndex = query.record().indexOf("Picture")
    picture = query.value(picIndex).toByteArray()
    picturePixmap = QPixmap()
    picturePixmap.loadFromData(picture)
    return picturePixmap
示例#15
0
def get_Team_Pic(team):
    query = QSqlQuery ("SELECT * FROM team WHERE name = '" +team + "'")
    query.next()
    picIndex = query.record().indexOf("Picture")
    picture = query.value(picIndex).toByteArray()
    picturePixmap = QPixmap()
    picturePixmap.loadFromData(picture)
    return picturePixmap
示例#16
0
 def getChampionIconImages(self, clist):
     pixmap_list = {}
     for champ in clist.values():
         pixmap = QPixmap()
         pixmap.loadFromData(
             self.summoner.getImage('champion', champ['key'] + '.png'))
         pixmap_list[champ['name']] = pixmap
     return pixmap_list
示例#17
0
 def load(self):
     xpm = QPixmap()
     xpm.loadFromData(self.getFile('text.xpm').read())
     winIcon = QIcon(xpm)
     self.winManager = TextEditorManager(SimuVis4.Globals.mainWin.workSpace, TextEditorWindow.TextEditorWindow,
         QCoreApplication.translate('TextEditor', "Unnamed Textfile"), winIcon)
     self.winManager.initMain(SimuVis4.Globals.mainWin)
     return True
示例#18
0
def load_pixmap(path, apply_mask=False):
    if image_data != None:
        data = QByteArray.fromBase64(image_data[path][1])
        pixmap = QPixmap()
        pixmap.loadFromData(data, image_data[path][0])
    else:
        absolute_path = os.path.join(get_resources_path(), path)
        pixmap = QPixmap(absolute_path)

    return pixmap
示例#19
0
def load_pixmap(path, apply_mask=False):
    if image_data != None:
        data = QByteArray.fromBase64(image_data[path][1])
        pixmap = QPixmap()
        pixmap.loadFromData(data, image_data[path][0])
    else:
        absolute_path = os.path.join(get_resources_path(), path)
        pixmap = QPixmap(absolute_path)

    return pixmap
 def templateChanged(self, i):
     t = chartTemplates[i]
     self.templateInfo.setPlainText(t.description)
     n = uniqueName(t.chartName, self.sensorgroup.charts.keys(), numFormat="%d")
     self.nameInput.setText(n)
     if t.previewImage:
         xpm = QPixmap()
         path = os.path.join("previewImages", t.previewImage)
         data = self.ownPlugIn.getFile(path).read()
         xpm.loadFromData(data)
         self.templatePreview.setPixmap(xpm)
示例#21
0
文件: text.py 项目: 089git/calibre
 def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
     p = QPixmap()
     p.loadFromData(data, encoding, Qt.AutoColor)
     w, h = p.width(), p.height()
     p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0))
     if p.width() != xsize or p.height() != ysize:
         p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     QGraphicsPixmapItem.__init__(self, p)
     self.height, self.width = ysize, xsize
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
示例#22
0
	def readPicture(self, tree):
		"""
		Ließt das Charakterbild aus.
		"""

		pictureElement = tree.find("picture")
		if pictureElement is not None:
			imageData = QByteArray.fromBase64(str(pictureElement.text))
			image = QPixmap()
			image.loadFromData(imageData, Config.CHARACTER_PIC_FORMAT)
			self.__character.picture = image
示例#23
0
        def finished(response):
            self.access.finished.disconnect(finished)
            if response['isOk']:
                pixmap = QPixmap()
                pixmap.loadFromData(response['data'])
                response['pixmap'] = pixmap

                response['data'].clear()
                del response['data']
                del response['statusRequest']

            setFinished(response)
示例#24
0
 def load(self):
     xpm = QPixmap()
     xpm.loadFromData(self.getFile('text.xpm').read())
     winIcon = QIcon(xpm)
     self.winManager = TextEditorManager(SimuVis4.Globals.mainWin.workSpace, TextEditorWindow.TextEditorWindow,
         QCoreApplication.translate('TextEditor', 'Unnamed Textfile'), winIcon)
     self.winManager.initMain(SimuVis4.Globals.mainWin)
     ftActions = SimuVis4.Globals.fileTypeActions
     ftActions.addAction(self.winManager.openFile,
         ('application/simuvis4', 'text'),
         QCoreApplication.translate('TextEditor', 'Open in TextEditor'), 5)
     return True
示例#25
0
    def updateImage(self):

        try:
            url = self.github.get_user().avatar_url
        except (GithubException, AttributeError): 
            return 
        data = urllib.urlopen(url).read()
        pixmap = QPixmap()
        pixmap.loadFromData(data)
        self.activeUserAction.setIcon(QIcon(pixmap))
        self.userButtonMenu.setPixmap(pixmap)
        self.userButtonMenu.setText(self.github.get_user().login)
示例#26
0
    def updateImage(self):

        try:
            url = self.github.get_user().avatar_url
        except (GithubException, AttributeError):
            return
        data = urllib.urlopen(url).read()
        pixmap = QPixmap()
        pixmap.loadFromData(data)
        self.activeUserAction.setIcon(QIcon(pixmap))
        self.userButtonMenu.setPixmap(pixmap)
        self.userButtonMenu.setText(self.github.get_user().login)
示例#27
0
 def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
     p = QPixmap()
     p.loadFromData(data, encoding, Qt.AutoColor)
     w, h = p.width(), p.height()
     p = p.copy(x0, y0, min(w, x1 - x0), min(h, y1 - y0))
     if p.width() != xsize or p.height() != ysize:
         p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio,
                      Qt.SmoothTransformation)
     QGraphicsPixmapItem.__init__(self, p)
     self.height, self.width = ysize, xsize
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
 def templateChanged(self, i):
     t = chartTemplates[i]
     self.templateInfo.setPlainText(t.description)
     n = t.chartName
     while n in self.sensorgroup.charts.keys():
         n += '_X'
     self.nameInput.setText(n)
     if t.previewImage:
         xpm = QPixmap()
         path = os.path.join('previewImages', t.previewImage)
         data = self.ownPlugIn.getFile(path).read()
         xpm.loadFromData(data)
         self.templatePreview.setPixmap(xpm)
示例#29
0
 def displayIcon(self, summoner_name):
     iconName = self.summoner.getIcon(summoner_name)
     iconPixmap = QPixmap()
     self.icon_label.setStyleSheet(
         "QLabel {border-style: outset; border-width: 3px; border-color: gold}"
     )
     try:
         iconPixmap.loadFromData(
             self.summoner.getImage('profileicon', iconName))
         self.icon_label.setPixmap(iconPixmap)
     except RiotError:
         iconPixmap.load("./images/no_image.png")
         self.icon_label.setPixmap(iconPixmap)
示例#30
0
    def gifReceived(self, screen, data):
        pixmap = QPixmap()
        print "Data:", len(data)  #, data[0:5], data[-3:]
        pixmap.loadFromData(data)
        s = pixmap.size()
        print "Size:", s.width(), s.height()

        if screen == 0:
            self.screen.setGraphsPixmap(pixmap)
        elif screen == 1:
            self.screen.setMenuPixmap(pixmap)
        elif screen == 2:
            self.screen.setStatusPixmap(pixmap)
示例#31
0
def bmp_to_pixmap(path):
    if image_data is not None:
        data = QByteArray.fromBase64(image_data[path][1])
        pixmap = QPixmap()
        pixmap.loadFromData(data, image_data[path][0])
    else:
        absolute_path = os.path.join(get_program_path(), path)
        pixmap = QPixmap(absolute_path)

    mask1 = pixmap.createMaskFromColor(QColor(0xFF, 0x00, 0xF0), Qt.MaskInColor)
    pixmap.setMask(mask1)

    return pixmap
    def zoom_img(self, i, visit_id, event_id):

        handeler_index = i

        self.dlg_gallery_zoom = GalleryZoom()
        utils_giswater.setDialog(self.dlg_gallery_zoom)
        self.load_settings(self.dlg_gallery_zoom)
        self.lbl_img = self.dlg_gallery_zoom.findChild(QLabel, "lbl_img_zoom")

        # Parse a URL into components
        url = urlparse.urlsplit(str(self.img_path_list[self.start_indx][i]))

        # Check if path is URL
        if url.scheme == "http" or url.scheme == "https":
            url = str(self.img_path_list[self.start_indx][i])
            data = urllib2.urlopen(url).read()
            pixmap = QPixmap()
            pixmap.loadFromData(data)
        else:
            pixmap = QPixmap(str(self.img_path_list[self.start_indx][i]))

        self.lbl_img.setPixmap(pixmap)

        # lbl_img.show()
        zoom_visit_id = self.dlg_gallery_zoom.findChild(QLineEdit, "visit_id")
        zoom_event_id = self.dlg_gallery_zoom.findChild(QLineEdit, "event_id")

        zoom_visit_id.setText(str(visit_id))
        zoom_event_id.setText(str(event_id))

        self.btn_slidePrevious = self.dlg_gallery_zoom.findChild(
            QPushButton, "btn_slidePrevious")
        self.btn_slideNext = self.dlg_gallery_zoom.findChild(
            QPushButton, "btn_slideNext")
        self.set_icon(self.btn_slidePrevious, "109")
        self.set_icon(self.btn_slideNext, "108")

        self.dlg_gallery_zoom.rejected.connect(
            partial(self.close_dialog, self.dlg_gallery_zoom))

        self.i = i
        self.btn_slidePrevious.clicked.connect(self.slide_previous)
        self.btn_slideNext.clicked.connect(self.slide_next)

        # Open dialog
        self.open_dialog(self.dlg_gallery_zoom, maximize_button=False)

        # Controling start index
        if handeler_index != i:
            self.start_indx = self.start_indx + 1
示例#33
0
 def load(self):
     import GraphicsWindow, Items
     self.GraphicsWindow = GraphicsWindow
     self.Items = Items
     xpm = QPixmap()
     xpm.loadFromData(self.getFile('graphicswin.xpm').read())
     winIcon = QIcon(xpm)
     self.winManager = SubWinManager(SimuVis4.Globals.mainWin.workSpace, self.GraphicsWindow.GraphicsWindow,
         QCoreApplication.translate('Graphics', "GraphicsView"), winIcon)
     testAction = QAction(winIcon,
         QCoreApplication.translate('Graphics', '&Graphics Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('Graphics', 'Show a new graphics window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
示例#34
0
def openimage(url):
    key = url.toString().lstrip('file://')
    try:
        data, imagetype = images[os.path.basename(key)]
    except KeyError:
        # It's not a image so lets just pass it of as a normal
        # URL
        QDesktopServices.openUrl(url)
        return

    pix = QPixmap()
    if imagetype == 'base64':
        pix.loadFromData(data)
    else:
        pix.load(data)
    utils.openImageViewer(pix)
示例#35
0
    def loadImage(self, data, scaled=True, fromfile=True):
        """
            Load the image into the widget using a bytearray

            An empty picture will result in the default placeholder
            image.
        """
        if data is None or not data:
            self.removeImage()
            return

        if fromfile:
            pix = QPixmap(data)
        elif isinstance(data, QPixmap):
            pix = data
        else:
            pix = QPixmap()
            r = pix.loadFromData(data, 'JPG')
            if not r:
                pix = QPixmap(data)

        self._orignalimage = QPixmap(pix)

        h = self.maximumHeight()
        if scaled:
            pix = pix.scaledToHeight(h, Qt.SmoothTransformation)

        self.image.setPixmap(pix)
        self.isDefault = False
示例#36
0
    def loadImage(self, data, scaled=True, fromfile=True):
        """
            Load the image into the widget using a bytearray

            An empty picture will result in the default placeholder
            image.
        """
        if data is None or not data:
            self.removeImage()
            return

        if fromfile:
            pix = QPixmap(data)
        elif isinstance(data, QPixmap):
            pix = data
        else:
            pix = QPixmap()
            r = pix.loadFromData(data, "JPG")
            if not r:
                pix = QPixmap(data)

        self._orignalimage = QPixmap(pix)

        h = self.maximumHeight()
        if scaled:
            pix = pix.scaledToHeight(h, Qt.SmoothTransformation)

        self.image.setPixmap(pix)
        self.isDefault = False
示例#37
0
 def store_data(self, id, data):
     directory = ApplicationData.get('images')
     filename = os.path.join(directory, id + '.png')
     makedirs(directory)
     pixmap = QPixmap()
     if data is not None and pixmap.loadFromData(data):
         image_size = pixmap.size()
         if image_size.width() > self.max_size or image_size.height(
         ) > self.max_size:
             pixmap = pixmap.scaled(self.max_size, self.max_size,
                                    Qt.KeepAspectRatio,
                                    Qt.SmoothTransformation)
         if imghdr.what(None, data) != 'png' or pixmap.size() != image_size:
             buffer = QBuffer()
             pixmap.save(buffer, 'png')
             data = str(buffer.data())
         with open(filename, 'wb') as f:
             f.write(data)
         icon = QIcon(pixmap)
         icon.filename = filename
         icon.content = data
     else:
         unlink(filename)
         icon = None
     self.iconmap[id] = icon
     return icon
示例#38
0
文件: art.py 项目: Governa/Camelot
 def getQPixmap(self):
     """QPixmaps can only be used in the gui thread"""
     if self._cached_pixmap:
         return self._cached_pixmap
     from camelot.core.resources import resource_string
     from PyQt4.QtGui import QPixmap
     qpm = QPixmap()
     p = os.path.join('art', self._path)
     try:
         # For some reason this throws a unicode error if the path contains an accent (cf windows username)
         #  this happens only here, not for icons further on in the application
         #  so they see no splash screen, tant pis
         r = resource_string(self._module_name, p)
         qpm.loadFromData(r)
     except Exception, e:
         logger.warn(u'Could not load pixmap "%s" from module: %s, encountered exception' % (p, self._module_name), exc_info=e)
示例#39
0
 def store_image(self, data):
     if data is None:
         return None
     data_hash = sha512(data).hexdigest()
     try:
         return self.filemap[data_hash].destination
     except KeyError:
         pass
     try:
         destination_name = os.path.join('images', self.available_names.popleft())
     except IndexError:
         # No more available file names.
         return None
     pixmap = QPixmap()
     if pixmap.loadFromData(data):
         pixmap = pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation)
     makedirs(ApplicationData.get('images'))
     if pixmap.save(ApplicationData.get(destination_name)):
         file_mapping = FileMapping(data_hash, destination_name)
         self.filemap[data_hash] = file_mapping
         map_filename = ApplicationData.get(os.path.join('images', '.cached_icons.map'))
         map_tempname = map_filename + '.tmp'
         try:
             file = open(map_tempname, 'wb')
             pickle.dump(self.filemap, file)
             file.close()
             if sys.platform == 'win32':
                 unlink(map_filename)
             os.rename(map_tempname, map_filename)
         except Exception, e:
             log.error("could not save icon cache file mappings: %s" % e)
         return destination_name
示例#40
0
    def pixmapReceived(self, reply):
        """ Slot for handling the return of the asynchronous image download. """
        if reply.error() != QNetworkReply.NoError:
            reply.deleteLater()
            return

        data = reply.readAll()
        pixmap = QPixmap()
        pixmap.loadFromData(data)
        # The original image is stored as an attribute and drawn manually
        # using an overridden paintEvent.  This is preferable to using the
        # setPixmap() functionality of QLabels because it allows more control
        # over the scaling of the pixmap and allows the size of the QLabel
        # to dictate the pixmap size, and not the other way around.
        self._original_pixmap = pixmap
        reply.deleteLater()
        self.update()
示例#41
0
 def pixmap(self, width=4, height=4, dpi=100):
     from matplotlib.figure import Figure
     from matplotlib.backends.backend_agg import FigureCanvasAgg
     import StringIO
     from PyQt4.QtGui import QPixmap#, QColor
     fig = Figure(figsize=(width, height), dpi=dpi)
     canvas = FigureCanvasAgg(fig) # needed for savefig below
     ax = fig.add_subplot(111)
     ax.set_xlabel(self.xlabel)
     ax.set_ylabel(self.ylabel)
     ax.set_title(self.title)
     ax.plot(self.timepoints, self.values, color=self.colour, label=self.title)
     file_like_object = StringIO.StringIO()
     fig.savefig(file_like_object, format='png')
     pixmap = QPixmap()
     pixmap.loadFromData(file_like_object.getvalue(), 'PNG')
     file_like_object.close()
     return pixmap
示例#42
0
 def load(self):
     self.initTranslations()
     import vtk, VtkWidget, VtkWindow, Objects, Helpers
     self.vtk = vtk
     self.VtkWidget = VtkWidget
     self.VtkWindow = VtkWindow
     self.Objects = Objects
     self.Helpers = Helpers
     xpm = QPixmap()
     xpm.loadFromData(self.getFile('3dwin.xpm').read())
     winIcon = QIcon(xpm)
     self.winManager = SubWinManager(SimuVis4.Globals.mainWin.workSpace, self.VtkWindow.VtkWindow,
             QCoreApplication.translate('VtkWindow', "Vtk Window"), winIcon)
     testAction = QAction(winIcon,
         QCoreApplication.translate('VtkWindow', '&VtkWindow Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('VtkWindow', 'Show a new Vtk test window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
示例#43
0
文件: module.py 项目: Peziman/pyCAR
    def setBackground(self):
        try:
            source = Image.open(self.settings["path"] + "/" +
                                self.settings["album"] + "/covers/" +
                                str(self.settings["song"]) + ".jpg")
            source = source.filter(ImageFilter.GaussianBlur(4))
            if source.width < 700:
                width = 700
                height = int(width * (source.height / source.width))
                source = source.resize((width, height), Image.ANTIALIAS)
                top = int((height - 480) / 2)
                bottom = int(height - top)
                box = [0, top, 700, bottom]
                source = source.crop(box)
            elif source.height < 480:
                pass
            else:
                left = int((source.width - 700) / 2)
                right = int(source.width - left)
                top = int((source.height - 480) / 2)
                bottom = int(source.height - top)
                box = [left, top, right, bottom]
                source = source.crop(box)

            ### Bild dunkler machen ###
            im = source.split()
            R, G, B = 0, 1, 2
            constant = 1.5  # constant by which each pixel is divided
            Red = im[R].point(lambda i: i / constant)
            Green = im[G].point(lambda i: i / constant)
            Blue = im[B].point(lambda i: i / constant)
            source = Image.merge(source.mode, (Red, Green, Blue))

            imgByteArr = io.BytesIO()
            source.save(imgByteArr, format='JPEG')
            image = imgByteArr.getvalue()
            pixmap = QPixmap()
            pixmap.loadFromData(image, "JPEG", Qt.AutoColor)
            self.backgroundImage.setPixmap(pixmap)

        except:
            pixmap = QPixmap()
            self.backgroundImage.setPixmap(pixmap)
示例#44
0
 def getQPixmap(self):
     """QPixmaps can only be used in the gui thread"""
     if self._cached_pixmap:
         return self._cached_pixmap
     from camelot.core.resources import resource_string
     from PyQt4.QtGui import QPixmap
     qpm = QPixmap()
     p = os.path.join('art', self._path)
     try:
         # For some reason this throws a unicode error if the path contains an accent (cf windows username)
         #  this happens only here, not for icons further on in the application
         #  so they see no splash screen, tant pis
         r = resource_string(self._module_name, p)
         qpm.loadFromData(r)
     except Exception, e:
         logger.warn(
             u'Could not load pixmap "%s" from module: %s, encountered exception'
             % (p, self._module_name),
             exc_info=e)
示例#45
0
 def loadUserMenu(self):
     
     action = None
     for _, username, token in generate_tokens(CONFIG_PATH, 'github'):
         
         try:
             url = Github(token).get_user().avatar_url
         except (GithubException, AttributeError): 
             action = QAction(username, self, triggered=self.changeActive)
             self.userButtonMenu.addAction(action)
             continue
         data = urllib.urlopen(url).read()
         pixmap = QPixmap()
         pixmap.loadFromData(data)
         action = QAction(QIcon(pixmap), username, self,
                 triggered=self.changeActive)
         action.setIconVisibleInMenu(True)
         self.userButtonMenu.addAction(action)
     
     self.activeUserAction = action
示例#46
0
 def getMasteryImages(self, masteryList):
     pixmap_list = collections.OrderedDict()
     empty_spaces = 0
     for row in masteryList:
         if len(row['masteryTreeItems']) == 2:
             #if len(row) == 3:
             row['masteryTreeItems'].append(None)
             #row.append(None)
         for element in row['masteryTreeItems']:
             #for element in row:
             if element != None:
                 pixmap = QPixmap()
                 pixmap.loadFromData(
                     self.summoner.getImage(
                         'mastery',
                         str(element['masteryId']) + '.png'))
                 pixmap_list[element['masteryId']] = pixmap
             else:
                 pixmap_list['null' + str(empty_spaces)] = None
                 empty_spaces += 1
     return pixmap_list
示例#47
0
    def try_image(value):
        _, extension = os.path.splitext(value)
        if extension[1:].lower() in supportedformats:
            if not os.path.exists(value):
                value = os.path.join(kwargs.get('imagepath', ''), value)
            return image_handler(key, value, imagetype='file')

        base64 = QByteArray.fromBase64(value)
        image = QPixmap()
        loaded = image.loadFromData(base64)
        if loaded:
            return image_handler(key, base64, imagetype='base64')
示例#48
0
 def load(self):
     self.initTranslations()
     cfg = SimuVis4.Globals.config
     cfgsec = self.name.lower()
     if not cfg.has_section(cfgsec):
         cfg.add_section(cfgsec)
     glb = SimuVis4.Globals
     import QwtPlotWindow, QPlot, MaskedArray
     self.QwtPlotWindow = QwtPlotWindow
     self.MaskedArray = MaskedArray
     xpm = QPixmap()
     xpm.loadFromData(self.getFile('plotwin.xpm').read())
     winIcon = QIcon(xpm)
     self.winManager = SubWinManager(SimuVis4.Globals.mainWin.workSpace, QwtPlotWindow.QwtPlotWindow,
             QCoreApplication.translate('QwtPlot', 'Qwt Plotwindow'), winIcon)
     testAction = QAction(winIcon,
         QCoreApplication.translate('QwtPlot', '&QwtPlotWindow Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('QwtPlot', 'Show a new Qwt test window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
示例#49
0
    def try_image(value):
        _, extension = os.path.splitext(value)
        if extension[1:].lower() in supportedformats:
            if not os.path.exists(value):
                value = os.path.join(kwargs.get('imagepath', ''), value)
            return image_handler(key, value, imagetype='file')

        newvalue = value.encode("utf-8")
        base64 = QByteArray.fromBase64(newvalue)
        image = QPixmap()
        loaded = image.loadFromData(base64)
        if loaded:
            return image_handler(key, base64, imagetype='base64')
示例#50
0
    def loadUserMenu(self):

        action = None
        for _, username, token in generate_tokens(CONFIG_PATH, 'github'):

            try:
                url = Github(token).get_user().avatar_url
            except (GithubException, AttributeError):
                action = QAction(username, self, triggered=self.changeActive)
                self.userButtonMenu.addAction(action)
                continue
            data = urllib.urlopen(url).read()
            pixmap = QPixmap()
            pixmap.loadFromData(data)
            action = QAction(QIcon(pixmap),
                             username,
                             self,
                             triggered=self.changeActive)
            action.setIconVisibleInMenu(True)
            self.userButtonMenu.addAction(action)

        self.activeUserAction = action
示例#51
0
文件: mainwindow.py 项目: SFrav/Roam
    def viewurl(self, url):
        """
        Open a URL in Roam
        :param url:
        :return:
        """
        key = url.toString().lstrip('file://')
        try:
            # Hack. Eww fix me.
            data, imagetype = roam.htmlviewer.images[os.path.basename(key)]
        except KeyError:
            # It's not a image so lets just pass it of as a normal
            # URL
            QDesktopServices.openUrl(url)
            return

        pix = QPixmap()
        if imagetype == 'base64':
            pix.loadFromData(data)
        else:
            pix.load(data)

        self.openimage(pix)
 def viewurl(self, url):
     """
     Open a URL in Roam
     :param url:
     :return:
     """
     key = url.toString().lstrip('file://')
     try:
         # Hack. Eww fix me.
         data, imagetype = roam.htmlviewer.images[os.path.basename(key)]
         pix = QPixmap()
         if imagetype == 'base64':
             pix.loadFromData(data)
         else:
             pix.load(data)
         self.openimage(pix)
     except KeyError:
         pix = QPixmap()
         pix.load(key)
         if pix.isNull():
             QDesktopServices.openUrl(url)
             return
         self.openimage(pix)
示例#53
0
 def viewurl(self, url):
     """
     Open a URL in Roam
     :param url:
     :return:
     """
     key = url.toString().lstrip('file://')
     try:
         # Hack. Eww fix me.
         data, imagetype = roam.htmlviewer.images[os.path.basename(key)]
         pix = QPixmap()
         if imagetype == 'base64':
             pix.loadFromData(data)
         else:
             pix.load(data)
         self.openimage(pix)
     except KeyError:
         pix = QPixmap()
         pix.load(key)
         if pix.isNull():
             QDesktopServices.openUrl(url)
             return
         self.openimage(pix)
示例#54
0
def string_handler(key, value):
    global supportedformats
    if not supportedformats:
        supportedformats = [f.data() for f in QImageReader.supportedImageFormats()]

    base64 = QByteArray.fromBase64(value)
    image = QPixmap()
    loaded = image.loadFromData(base64)
    if loaded:
        return image_handler(key, base64, imagetype='base64')
    _, extension = os.path.splitext(value)
    if extension[1:] in supportedformats:
        return image_handler(key, value, imagetype='file')

    return value
示例#55
0
 def getQPixmap(self):
     """QPixmaps can only be used in the gui thread"""
     if self._cached_pixmap:
         return self._cached_pixmap
     from camelot.core.resources import resource_string
     from PyQt4.QtGui import QPixmap
     qpm = QPixmap()
     success = qpm.loadFromData(resource_string(self._module_name,
                                                'art/%s'%(self._path),
                                                'CAMELOT_MAIN_DIRECTORY'))
     if not success:
         msg = u'Could not load pixmap %s from camelot art library'
         logger.warn(msg % self._path)
     self._cached_pixmap = qpm
     return qpm
示例#56
0
    def loadImage(self, data):
        """
            Load the image into the widget using a bytearray

            An empty picture will result in the default placeholder
            image.
        """
        if data is None or not data:
            self.removeImage()
            return

        pix = QPixmap()
        r = pix.loadFromData(data, 'JPG')
        self.image.setScaledContents(True)
        self.image.setPixmap(pix)
        self.isDefault = False