def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) 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
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
def getSongs(self): album = self.albumList.currentItem().text() self.lbl_currentAlbum.setText(album) self.musicList.clear() self.musicList.clearSelection() for item in music[album]: itm = QtGui.QListWidgetItem(music[album][item]["title"]) if not os.path.isdir(self.settings["path"] + "/" + album + "/covers"): os.mkdir(self.settings["path"] + "/" + album + "/covers", 777) image = self.settings["path"] + "/" + album + "/covers/" + str( item) + ".jpg" if not os.path.isfile(image): file = File( music[album][item]["path"] ) # mutagen can automatically detect format and type of tags try: artwork = file.tags[ 'APIC:'].data # access APIC frame and grab the image new = QImage() new.loadFromData(artwork) pixmap = QPixmap(new).scaledToHeight( 500, Qt.SmoothTransformation) pixmap.save(image, "JPG") except: image = r"./images/nocover.png" itm.setIcon(QIcon(image)) itm.setSelected(False) self.musicList.addItem(itm) if album == self.settings["album"]: self.musicList.setCurrentRow(self.settings["song"]) self.stack.setCurrentIndex(2)
def save_image(): try: page = web.page() frame = page.currentFrame() # Grow the viewport to make it fit the whole document width = min_width height = min_height page.setViewportSize(QSize(width, height)) while frame.scrollBarMaximum(Qt.Horizontal) != 0: width += 1 page.setViewportSize(QSize(width, height)) while frame.scrollBarMaximum(Qt.Vertical) != 0: height += 1 page.setViewportSize(QSize(width, height)) # Render the document to an image file image = QPixmap(width, height) painter = QPainter() painter.begin(image) frame.render(painter) painter.end() image.save(dest, format, quality) finally: QApplication.exit()
def updateThumbnail(self, node, pixmap): if pixmap == None: pixmap = QPixmap(":file_broken.png") pixmap.save(self.qbuffer, 'JPG') self.qbuffer.seek(0) QTimer.singleShot(0, self, SIGNAL("readyRead()")) QTimer.singleShot(0, self, SIGNAL("finished()"))
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
def get_favicon( host, ico_path): fail_pixmap = QPixmap(':/app/text-html.png') if not os.path.exists(ico_path): import urllib u = urllib.urlopen('http://favicon.yandex.net/favicon/%s'%host).read() #http://www.google.com/s2/favicons?domain=www.labnol.org tmp = open( '/tmp/tmp.png','w+b') tmp.write( u ) tmp.close() pixmap = QPixmap("/tmp/tmp.png") if pixmap.size() == QtCore.QSize(1, 1): pixmap = fail_pixmap tmp_ico = QIcon( pixmap ) pixmap.save( QString( ico_path) ) return tmp_ico
def thumbnailPhoto(self, imagePath, tp): if os.path.exists(tp): return QPixmap(tp) else: if os.path.exists(os.path.dirname(tp)) == False: os.mkdir(os.path.dirname(tp)) pixmap = QPixmap(imagePath).scaled(800, 600).scaled( 75, 50, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) a = pixmap.save(tp, 'PNG') return pixmap
def crop_pixmaps(path, mask, pretend=False): """ crop all pixmaps in a dir according to a masks. This function does nothing in regards to validating modules. If the pixmaps exist and an entry exists in masks, the pixmaps get chopped. """ from PyQt4.QtGui import QPixmap for fname in os.listdir(path): if extension(fname) == 'png': fpath = os.path.join(path, fname) pixmap = QPixmap(fpath) x, y, w, h = mask[0], mask[1], mask[2], mask[3] if pixmap.isNull() is False and \ pixmap.width() > w and \ pixmap.height() > h: pixmap = pixmap.copy(x, y, w, h) if pretend: print 'PRETEND:', else: pixmap.save(fpath, 'PNG') print 'wrote %s x=%i y=%i w=%i h=%i' % (fpath, x, y, w, h)
def saveImage(self,paintedScene): w = paintedScene.width(); h = paintedScene.height(); paintedScene.setBackgroundBrush(self.whitebrush); view = QGraphicsView(); view.setScene(paintedScene) outputimg = QPixmap(w, h) painter = QPainter(outputimg) targetrect = QRectF(0, 0, w, h) sourcerect = QRect(0, 0, w, h) view.render(painter, targetrect, sourcerect) filename = "NET_VIS_"+ commons.getStrTimeStamp()+".jpg"; outputimg.save(filename, "JPG") painter.end()
def process(self, fullpath, image_dataurl, polylines): image_data, _ = mio.extract_image_and_type(image_dataurl) image = QtGui.QImage() image.loadFromData(image_data) sis = image.size() pixmap = QPixmap(sis.width(), sis.height()) pixmap.fill(Qt.white) p = QPainter() p.begin(pixmap) p.drawImage(QPoint(0, 0), image) p.setRenderHint(QPainter.Antialiasing) p.setPen(Qt.yellow) for polyline in polylines: self._draw_polyline(p, polyline) p.end() _, fname = path.split(fullpath) outpath = path.join(self.outdir, fname) print(outpath) pixmap.save(outpath) return [fullpath, image_dataurl, polylines]
def save_png (filename, sc, background = (255,255,255, 0) ) : """Create a png image from a scene :Parameters: - `filename` (str) - name to write the image - `sc` (SVGScene) - `background` (int, int, int, int) - background color as (R, G, B, alpha) 0-255 tuple """ qapp = QApplication.instance() if qapp is None : qapp = QApplication([]) r = QSvgRenderer(None) data = QByteArray(str(to_xml(sc) ) ) r.load(data) pix = QPixmap(r.defaultSize() ) pix.fill(QColor(*background) ) painter = QPainter(pix) r.render(painter) painter.end() pix.save(filename)
def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) 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
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
def save_png(filename, sc, background=(255, 255, 255, 0)): """Create a png image from a scene :Parameters: - `filename` (str) - name to write the image - `sc` (SVGScene) - `background` (int, int, int, int) - background color as (R, G, B, alpha) 0-255 tuple """ qapp = QApplication.instance() if qapp is None: qapp = QApplication([]) r = QSvgRenderer(None) data = QByteArray(str(to_xml(sc))) r.load(data) pix = QPixmap(r.defaultSize()) pix.fill(QColor(*background)) painter = QPainter(pix) r.render(painter) painter.end() pix.save(filename)
def store(self, filename, pixmap=None): if filename is None: return None if not os.path.isabs(filename): return filename if filename.startswith(ApplicationData.directory + os.path.sep): return filename[len(ApplicationData.directory + os.path.sep):] try: file_mapping = self.filemap[filename] except KeyError: pass else: source_info = FileInfo(filename) destination_info = FileInfo(file_mapping.destination.name) if (source_info, destination_info) == (file_mapping.source, file_mapping.destination): return destination_info.name try: destination_name = os.path.join('images', self.available_names.popleft()) except IndexError: # No more available file names. Return original file for now return filename if pixmap is None: pixmap = QPixmap() if pixmap.load(filename): pixmap = pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation) makedirs(ApplicationData.get('images')) if pixmap.save(ApplicationData.get(destination_name)): source_info = FileInfo(filename) destination_info = FileInfo(destination_name) file_mapping = FileMapping(source_info, destination_info) self.filemap[filename] = 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
def take_screenshot(self, path): pixmap = QPixmap(QPixmap.grabWidget(self.display)) pixmap.save(path) self.logger.debug('Saving {}'.format(path))
class ScreenShot(QWidget): def __init__(self): super(ScreenShot, self).__init__() self.initUI() def initUI(self): self.originalPixmap = QPixmap() self.screenshotLabel = QLabel("screenshotlabel", self) self.screenshotLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.screenshotLabel.setAlignment(Qt.AlignCenter) self.screenGeometry = QApplication.desktop().screenGeometry( ) # Qrect() print self.screenGeometry, self.screenGeometry.width() self.screenshotLabel.setMinimumSize(self.screenGeometry.width() / 8, self.screenGeometry.height() / 8) mainlayout = QVBoxLayout(self) mainlayout.addWidget(self.screenshotLabel) self.optionsGroupBox = QGroupBox(u"选项", self) self.hideThisWindowCheckBox = QCheckBox(u"隐藏这个窗口", self.optionsGroupBox) self.optionsGroupBoxLayout = QGridLayout(self.optionsGroupBox) mainlayout.addWidget(self.optionsGroupBox) self.delaySpinBox = QSpinBox(self.optionsGroupBox) self.delaySpinBox.setSuffix(u"s") self.delaySpinBox.setMaximum(60) self.optionsGroupBoxLayout.addWidget(QLabel(u"截屏延时:", self), 0, 0) self.optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1) self.optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0) buttonLayout = QHBoxLayout() self.newScreenshotButton = QPushButton(u"新截图", self) self.newScreenshotButton.clicked.connect(self.__newScreenshot) buttonLayout.addWidget(self.newScreenshotButton) saveScreenshotButton = QPushButton(u"保存截图", self) buttonLayout.addWidget(saveScreenshotButton) quitScreenshotButton = QPushButton(u"退出截图", self) quitScreenshotButton.setShortcut("Ctrl+Q") buttonLayout.addWidget(saveScreenshotButton) buttonLayout.addStretch() mainlayout.addLayout(buttonLayout) quitScreenshotButton.clicked.connect(self.close) saveScreenshotButton.clicked.connect(self.__saveScreenshot) self.delaySpinBox.valueChanged.connect(self.__updateCheckBox) self.delaySpinBox.setValue(5) self.setWindowTitle(u"截图") self.resize(300, 200) def resizeEvent(self, QResizeEvent): scaledSize = self.originalPixmap.size() scaledSize.scale(self.screenshotLabel.size(), Qt.KeepAspectRatio) if (not self.screenshotLabel.pixmap()) or ( scaledSize != self.screenshotLabel.pixmap().size()): self.__updateScreenshotLabel() def __newScreenshot(self): if self.hideThisWindowCheckBox.isChecked(): self.hide() self.newScreenshotButton.setDisabled(True) QTimer.singleShot(self.delaySpinBox.value() * 1000, self.__shootScreen) def __saveScreenshot(self): format = "png" initialPath = QDesktopServices.storageLocation( QDesktopServices.PicturesLocation) # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); if initialPath.isEmpty(): initialPath = QDir.currentPath() initialPath += "/untitled." + format fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath) fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) fileDialog.setFileMode(QtGui.QFileDialog.AnyFile) fileDialog.setDirectory(initialPath) mimeTypes = QStringList() for bf in QImageWriter.supportedImageFormats(): mimeTypes.append(QLatin1String(bf)) # fileDialog.setMin setMimeTypeFilters(mimeTypes) # fileDialog.selectMimeTypeFilter("image/" + format); fileDialog.setDefaultSuffix(format) if fileDialog.accept(): return fileName = fileDialog.selectedFiles().first() if not self.originalPixmap.save(fileName): QtGui.QMessageBox.Warning( self, u"保存错误", u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName))) def __shootScreen(self): if self.delaySpinBox.value() != 0: QApplication.beep() self.originalPixmap = QPixmap.grabWindow( QApplication.desktop().winId()) self.__updateScreenshotLabel() self.newScreenshotButton.setDisabled(False) if self.hideThisWindowCheckBox.isChecked(): self.show() def __updateCheckBox(self): print "sssss" if self.delaySpinBox.value() == 0: self.hideThisWindowCheckBox.setDisabled(True) self.hideThisWindowCheckBox.setChecked(False) else: self.hideThisWindowCheckBox.setDisabled(False) def __updateScreenshotLabel(self): self.screenshotLabel.setPixmap( self.originalPixmap.scaled(self.screenshotLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
painter.fillRect(xb - bl, yb - bt, bl + (pw + gw) * 5 - gw + br, bt + (ph + gh) * 8 - gh + bb, background) painter.drawText(xb, yb + ch, (pw + gw) * 5 - gw, 100, Qt.AlignHCenter | Qt.TextDontClip, text) xo = 0 for cs in line.strip().split(',')[:5]: cs = cs.strip().split(' ')[0] ci = int(cs, base=16) for bit in range(8): if ci & (1 << bit) != 0: painter.fillRect(xb + xo, yb + (ph + gh) * bit, pw, ph, Qt.black) else: painter.fillRect(xb + xo, yb + (ph + gh) * bit, pw, ph, Qt.lightGray) xo += pw + gw yb += (ph + gh) * 8 - gh + bb + bt counter += 1 if counter % 16 == 0: xb += (pw + gw) * 5 - gw + br + bl yb = Bt + bt painter.end() pixmap.save('font.png', 'PNG')
text = (u'%02X' % counter) + u'\u2095' background = Qt.white if counter > 0: painter.fillRect(xb - bl, yb - bt, bl + (pw + gw) * 5 - gw + br, bt + (ph + gh) * 8 - gh + bb, background) painter.drawText(xb, yb + ch, (pw + gw) * 5 - gw, 100, Qt.AlignHCenter | Qt.TextDontClip, text) xo = 0 for cs in line.strip().split(',')[:5]: cs = cs.strip().split(' ')[0] ci = int(cs, base=16) for bit in range(8): if ci & (1 << bit) != 0: painter.fillRect(xb + xo, yb + (ph + gh) * bit, pw, ph, Qt.black) else: painter.fillRect(xb + xo, yb + (ph + gh) * bit, pw, ph, Qt.lightGray) xo += pw + gw yb += (ph + gh) * 8 - gh + bb + bt counter += 1 if counter % 16 == 0: xb += (pw + gw) * 5 - gw + br + bl yb = Bt + bt painter.end() pixmap.save('font.png', 'PNG')
def save_capture(self, filename): """Saves the current capture and its annotations to the given file.""" pixmap = QPixmap(self.window.center_view.size()) self.window.center_view.render(pixmap) pixmap.save(filename)
def take_screenshot(self, path): pixmap = QPixmap(QPixmap.grabWidget(self.display)) pixmap.save(path) self.logger.debug('Saving {}'.format(path))
def save_capture(self, filename): """Saves the current capture and its annotations to the given file.""" pixmap = QPixmap(self.window.center_view.size()) self.window.center_view.render(pixmap) pixmap.save(filename)