def updateData(self, obj, prop): if prop == "Color": from PySide import QtCore,QtGui # custom icon if hasattr(obj,"Color"): c = obj.Color matcolor = QtGui.QColor(int(c[0]*255),int(c[1]*255),int(c[2]*255)) darkcolor = QtGui.QColor(int(c[0]*125),int(c[1]*125),int(c[2]*125)) im = QtGui.QImage(48,48,QtGui.QImage.Format_ARGB32) im.fill(QtCore.Qt.transparent) pt = QtGui.QPainter(im) pt.setPen(QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine, QtCore.Qt.FlatCap)) #pt.setBrush(QtGui.QBrush(matcolor, QtCore.Qt.SolidPattern)) gradient = QtGui.QLinearGradient(0,0,48,48) gradient.setColorAt(0,matcolor) gradient.setColorAt(1,darkcolor) pt.setBrush(QtGui.QBrush(gradient)) pt.drawEllipse(6,6,36,36) pt.setPen(QtGui.QPen(QtCore.Qt.white, 1, QtCore.Qt.SolidLine, QtCore.Qt.FlatCap)) pt.setBrush(QtGui.QBrush(QtCore.Qt.white, QtCore.Qt.SolidPattern)) pt.drawEllipse(12,12,12,12) pt.end() ba = QtCore.QByteArray() b = QtCore.QBuffer(ba) b.open(QtCore.QIODevice.WriteOnly) im.save(b,"XPM") self.icondata = ba.data().decode("latin1")
def BlockTypePixmap(block, textureAtlas): """ :param block: :type block: mceditlib.blocktypes.BlockType :param textureAtlas: :type textureAtlas: mcedit2.rendering.textureatlas.TextureAtlas :return: :rtype: QtGui.QPixmap """ models = textureAtlas.blockModels texname = models.firstTextures.get(block.internalName + block.blockState) if texname is None: log.debug("No texture for %s!", block.internalName + block.blockState) texname = "MCEDIT_UNKNOWN" io = textureAtlas._openImageStream(texname) data = io.read() array = QtCore.QByteArray(data) buf = QtCore.QBuffer(array) reader = QtGui.QImageReader(buf) image = reader.read() pixmap = QtGui.QPixmap.fromImage(image) w = pixmap.width() h = pixmap.height() s = min(w, h) if w != h: pixmap = pixmap.copy(0, 0, s, s) if s != 32: pixmap = pixmap.scaledToWidth(32) return pixmap
def onChanged(self, vobj, prop): if hasattr(vobj, "OverrideLineColorChildren" ) and vobj.OverrideLineColorChildren: if hasattr(vobj, "Object") and hasattr(vobj.Object, "Group"): for o in vobj.Object.Group: if o.ViewObject: for p in [ "LineColor", "ShapeColor", "LineWidth", "DrawStyle", "Transparency" ]: if p == "ShapeColor": if hasattr( vobj, "OverrideShapeColorChildren" ) and vobj.OverrideShapeColorChildren: setattr(o.ViewObject, p, getattr(vobj, p)) else: if hasattr(vobj, p) and hasattr( o.ViewObject, p): setattr(o.ViewObject, p, getattr(vobj, p)) # give line color to texts if hasattr(vobj, "LineColor") and hasattr( o.ViewObject, "TextColor"): o.ViewObject.TextColor = vobj.LineColor if (prop == "Visibility") and hasattr(vobj, "Visibility"): if hasattr(vobj, "Object") and hasattr(vobj.Object, "Group"): for o in vobj.Object.Group: if o.ViewObject and hasattr(o.ViewObject, "Visibility"): o.ViewObject.Visibility = vobj.Visibility if (prop in ["LineColor", "ShapeColor"]) and hasattr( vobj, "LineColor") and hasattr(vobj, "ShapeColor"): from PySide import QtCore, QtGui lc = vobj.LineColor sc = vobj.ShapeColor lc = QtGui.QColor(int(lc[0] * 255), int(lc[1] * 255), int(lc[2] * 255)) sc = QtGui.QColor(int(sc[0] * 255), int(sc[1] * 255), int(sc[2] * 255)) p1 = QtCore.QPointF(2, 17) p2 = QtCore.QPointF(13, 8) p3 = QtCore.QPointF(30, 15) p4 = QtCore.QPointF(20, 25) im = QtGui.QImage(32, 32, QtGui.QImage.Format_ARGB32) im.fill(QtCore.Qt.transparent) pt = QtGui.QPainter(im) pt.setBrush(QtGui.QBrush(sc, QtCore.Qt.SolidPattern)) pt.drawPolygon([p1, p2, p3, p4]) pt.setPen(QtGui.QPen(lc, 2, QtCore.Qt.SolidLine, QtCore.Qt.FlatCap)) pt.drawPolygon([p1, p2, p3, p4]) pt.end() ba = QtCore.QByteArray() b = QtCore.QBuffer(ba) b.open(QtCore.QIODevice.WriteOnly) im.save(b, "XPM") self.icondata = ba.data().decode("latin1") vobj.signalChangeIcon()
def _qimage_to_pil_image(qimg): buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) qimg.save(buffer, "PNG") bytes_io = io.BytesIO() bytes_io.write(buffer.data().data()) buffer.close() bytes_io.seek(0) return Image.open(bytes_io)
def qimage_to_pil_image(self, img): buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) img.save(buffer, "PNG") strio = StringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) return Image.open(strio)
def convert_image(img): buffer1 = QtCore.QBuffer() buffer1.open(QtCore.QIODevice.ReadWrite) img.save(buffer1, "PNG") strio = cStringIO.StringIO() strio.write(buffer1.data()) buffer1.close() strio.seek(0) return Image.open(strio)
def shareScreen(self, host_data): """ Send screenshot """ self.trayIcon.setIconLoading() # capture screenshot screenBA = QtCore.QByteArray() screenBuf = QtCore.QBuffer(screenBA) screenBuf.open(QtCore.QBuffer.WriteOnly) QPixmap.grabWindow(self.desktop().winId()).save( screenBuf, SCREEN_IMAGE_TYPE, SCREEN_IMAGE_QUALITY) self.connector.submitScreen(host_data["host"], host_data["port"], screenBA)
def requestStarted(self, request): # Parse Url url = request.requestUrl() path = url.path() query = QtCore.QUrlQuery(url) params = {k: unquote(v) for k, v in query.queryItems()} # Fix Windows URL (This is insane) win_fix = WINDOWS_PATH_PATTERN.match(path) if win_fix: path = win_fix.group(1) # Prepare response buffer buf = QtCore.QBuffer(parent=self) request.destroyed.connect(buf.deleteLater) buf.open(QtCore.QIODevice.WriteOnly) # Match Action action = None action_match = ACTION_URL_PATTERN.match(path) if action_match: action = action_match.group(1) if path.endswith('.html') or action: # Prepare Response object response = Response(self, buf, request) request.destroyed.connect(response.deleteLater) # Call handler to do the real work # ! Important: requestHandler can work in another thread. # ! response.send() should be called from the handler # ! to send any content. self.requestHandler(path, action, params, request, response) else: file_path = Path(path) content_type = get_supported_mimetype(file_path) if file_path.exists(): with open(file_path, 'rb') as f: buf.write(f.read()) buf.seek(0) buf.close() request.reply(content_type.encode(), buf) else: buf.close() request.reply(content_type.encode(), buf) log("Path does not exists: ", str(file_path))
def set_avatar(self): choose = QtGui.QApplication.translate("ProfileSettingsForm", "Choose avatar", None, QtGui.QApplication.UnicodeUTF8) name = QtGui.QFileDialog.getOpenFileName(self, choose, None, 'Images (*.png)') if name[0]: bitmap = QtGui.QPixmap(name[0]) bitmap.scaled(QtCore.QSize(128, 128), aspectMode=QtCore.Qt.KeepAspectRatio, mode=QtCore.Qt.SmoothTransformation) byte_array = QtCore.QByteArray() buffer = QtCore.QBuffer(byte_array) buffer.open(QtCore.QIODevice.WriteOnly) bitmap.save(buffer, 'PNG') Profile.get_instance().set_avatar(str(byte_array.data()))
def __init__(self, parent=None): super(CucumberGifWidget, self).__init__(parent) self.setAcceptDrops(True) self.setFrameStyle(QtGui.QFrame.WinPanel | QtGui.QFrame.Sunken) self.setAlignment(QtCore.Qt.AlignCenter) self.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding) trashGif= open(os.path.join(ImagesFolder,'cucumber.gif'), 'rb').read() self.gifByteArray=QtCore.QByteArray(trashGif) self.gifBuffer=QtCore.QBuffer(self.gifByteArray) self.movie = QtGui.QMovie() self.movie.setFormat('GIF') self.movie.setDevice(self.gifBuffer) self.movie.setCacheMode(QtGui.QMovie.CacheAll) self.movie.setSpeed(100) self.setMovie(self.movie) self.movie.jumpToFrame(0)
def __init__(self, parent=None, data=None, data_fs=None, sample_freq=None, bd='float32', tick_interval=200): if bd not in bit_depths.values(): raise ValueError('Unsupported bit depth: %s' % bd) if tick_interval < 1: raise ValueError('tick_interval must be greater than zero.') super(PlayerToolBar, self).__init__(parent) self._audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self) self._mediaObject = Phonon.MediaObject(self) self._mediaObject.setTickInterval(tick_interval) self._mediaObject.aboutToFinish.connect(self.about_to_finish) self._mediaObject.finished.connect(self.finished) self._mediaObject.currentSourceChanged.connect( self.current_source_changed) self._mediaObject.tick.connect(self.on_tick) self._mediaObject.stateChanged.connect(self.state_changed) self.connected = False self.connect_path() self._buffer = QtCore.QBuffer() self.buffer_loaded = False self._start = 0 self._end = np.inf self._interval_selected = False self._raw_data = None self.bd = bd if sample_freq is not None: self.sample_freq = float(sample_freq) else: self.sample_freq = None self._real_freq = None if data is not None: self.load_data(data, data_fs) else: self.data = None self._data_fs = None self.data_loaded = False self._init_ui()
def mouseReleaseEvent(self, event): if self.rubberband.isVisible(): self.rubberband.hide() rect = self.rubberband.geometry() if rect.width() and rect.height(): p = QtGui.QPixmap.grabWindow( QtGui.QApplication.desktop().winId(), rect.x() + 4, rect.y() + 4, rect.width() - 8, rect.height() - 8) byte_array = QtCore.QByteArray() buffer = QtCore.QBuffer(byte_array) buffer.open(QtCore.QIODevice.WriteOnly) p.save(buffer, 'PNG') Profile.get_instance().send_screenshot(bytes( byte_array.data())) self.close()
def grabWindowPixmap(self): """ grabWindowImage() -> QPixmap Widget special grabbing function """ uchar = self.saveToPNG(None) ba = QtCore.QByteArray() buf = QtCore.QBuffer(ba) buf.open(QtCore.QIODevice.WriteOnly) for i in xrange(uchar.GetNumberOfTuples()): c = uchar.GetValue(i) buf.putChar(chr(c)) buf.close() pixmap = QtGui.QPixmap() pixmap.loadFromData(ba, 'PNG') return pixmap
def save_png_bytes_io(self): """ Save contents as PNG format file(BytesIO object) Note: DPI is platform dependent due to QPaintDevice DPI handling. Mac -> 72dpi, Ubuntu -> 96dpi """ bytearr = QtCore.QByteArray() buf = QtCore.QBuffer(bytearr) buf.open(QtCore.QIODevice.WriteOnly) self.contents.save(buf, "PNG") bio = io.BytesIO(bytearr.data()) # DPI correction img = Image.open(bio) img = img.resize((self.screen_size[0], self.screen_size[1]), Image.ANTIALIAS) img.info["dpi"] = (96, 96) converted = io.BytesIO() img.save(converted, format='png') return converted
def getIcon(self): self.p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Macro") self.macropath = self.p.GetString("MacroPath", "") if os.path.isfile(self.macropath + "/vise/vise.svg"): i = QtGui.QIcon(self.macropath + "/vise/vise.svg") else: vise_icon_url = "https://raw.githubusercontent.com/danielfalck/FCparametric/master/vise/vise.svg" vise_icon = utils.download(vise_icon_url, force=True) i = QtGui.QIcon(vise_icon) p = i.pixmap(128, 128) a = QtCore.QByteArray() b = QtCore.QBuffer(a) b.open(QtCore.QIODevice.WriteOnly) p.save(b, "XPM") b.close() return str(a)
def onChanged(self, vobj, prop): """Execute when a view property is changed.""" if prop in ("LineColor", "ShapeColor", "LineWidth", "DrawStyle", "Transparency", "Visibility"): self.change_view_properties(vobj, prop) if (prop in ("LineColor", "ShapeColor") and hasattr(vobj, "LineColor") and hasattr(vobj, "ShapeColor")): # This doesn't do anything to the objects inside the layer, # it just uses the defined Line and Shape colors # to paint the layer icon accordingly in the tree view l_color = vobj.LineColor s_color = vobj.ShapeColor l_color = QtGui.QColor(int(l_color[0] * 255), int(l_color[1] * 255), int(l_color[2] * 255)) s_color = QtGui.QColor(int(s_color[0] * 255), int(s_color[1] * 255), int(s_color[2] * 255)) p1 = QtCore.QPointF(2, 17) p2 = QtCore.QPointF(13, 8) p3 = QtCore.QPointF(30, 15) p4 = QtCore.QPointF(20, 25) image = QtGui.QImage(32, 32, QtGui.QImage.Format_ARGB32) image.fill(QtCore.Qt.transparent) pt = QtGui.QPainter(image) pt.setBrush(QtGui.QBrush(s_color, QtCore.Qt.SolidPattern)) pt.drawPolygon([p1, p2, p3, p4]) pt.setPen(QtGui.QPen(l_color, 2, QtCore.Qt.SolidLine, QtCore.Qt.FlatCap)) pt.drawPolygon([p1, p2, p3, p4]) pt.end() byte_array = QtCore.QByteArray() buffer = QtCore.QBuffer(byte_array) buffer.open(QtCore.QIODevice.WriteOnly) image.save(buffer, "XPM") self.icondata = byte_array.data().decode("latin1") vobj.signalChangeIcon()
def export_svg(self, path): buf = QtCore.QBuffer() generator = QtSvg.QSvgGenerator() generator.setOutputDevice(buf) generator.setFileName(path) generator.setTitle('Pywr') # TODO: this doesn't work as expected rect = self.scene.itemsBoundingRect() generator.setSize(self.size()) generator.setResolution(300) #generator.setSize(QtCore.QSize(600, 400)) #generator.setViewBox(QtCore.QRect(0, 0, rect.width(), rect.height())) # paint the scene painter = QtGui.QPainter() painter.begin(generator) painter.setRenderHint(QtGui.QPainter.Antialiasing) self.scene.render(painter) painter.end()
def capture_widget(widget, path=None): """Grab an image of a Qt widget Args: widget: The Qt Widget to capture path (optional): The path to save to. If not provided - will return image data. Returns: If a path is provided, the image will be saved to it. If not, the PNG buffer will be returned. """ pixmap = QtGui.QPixmap.grabWidget(widget) if path: pixmap.save(path) else: image_buffer = QtCore.QBuffer() image_buffer.open(QtCore.QIODevice.ReadWrite) pixmap.save(image_buffer, "PNG") return image_buffer.data().data()
def TexturePixmap(io, size=32, texname="Not provided"): try: data = io.read() array = QtCore.QByteArray(data) buf = QtCore.QBuffer(array) reader = QtGui.QImageReader(buf) image = reader.read() pixmap = QtGui.QPixmap.fromImage(image) if pixmap.isNull(): log.warn("File %s produced a null pixmap", texname) return None w = pixmap.width() h = pixmap.height() s = min(w, h) if w != h: pixmap = pixmap.copy(0, 0, s, s) if s != size: pixmap = pixmap.scaledToWidth(size) return pixmap except ValueError as e: log.warn("TexturePixmap: Failed to load texture %s: %r", texname, e)
def onClipChangeSlot(self): #test if identical #pmap = self.clipboard.pixmap() #text = self.clipboard.text() self.onSetStatusSlot(("scanning", "scan")) mimeData = self.clipboard.mimeData() if mimeData.hasImage(): #image = pmap.toImage() #just like wxpython do not allow this to del, or else .bits() will crash image = mimeData.imageData() prev = self.previous_hash #image.bits() crashes with OneNote large image copy hash = format( hash128(image.bits()), "x" ) ##http://stackoverflow.com/questions/16414559/trying-to-use-hex-without-0x #we want the large image out of memory asap, so just take a hash and gc collect the image PRINT("on clip change pmap", (hash, prev)) if hash == prev: #self.onSetStatusSlot(("image copied","good")) return #secure_hash = hashlib.new("ripemd160", hash + "ACCOUNT_SALT").hexdigest() #use pdkbf2 #to prevent rainbow table attacks of known files and their hashes, will also cause decryption to fail if file name is changed img_file_name = "%s.bmp" % hash img_file_path = os.path.join(self.CONTAINER_DIR, img_file_name) image.save(img_file_path) #change to or compliment upload pmap = QPixmap( image) #change to pixmap for easier image editing than Qimage pmap = PixmapThumbnail(pmap) device = QtCore.QBuffer( ) #is an instance of QIODevice, which is accepted by image.save() pmap.thumbnail.save( device, "PNG" ) # writes image into the in-memory container, rather than a file name bytearray = device.data() #get the buffer itself bytestring = bytearray.data() #copy the full string text = "Copied Image or Screenshot\n\n{w} x {h} Pixels\n{mp} Megapixels\n{mb} Megabytes".format( w=pmap.original_w, h=pmap.original_h, mp="%d.02" % (pmap.original_w * pmap.original_h / 1000000.0), mb="%d.1" % (pmap.original_w * pmap.original_h * 3 / 1024**2)) clip_display = dict( text=Binary(text), thumb=Binary( bytestring ) #Use BSON Binary to prevent UnicodeDecodeError: 'utf8' codec can't decode byte 0xeb in position 0: invalid continuation byte ) prepare = dict( file_names=[img_file_name], clip_display=clip_display, clip_type="screenshot", ) elif mimeData.hasHtml(): html = mimeData.html().encode("utf8") text = (mimeData.text() or "<Rich Text Data>").encode("utf8") prev = self.previous_hash hash = format(hash128(html), "x") PRINT("on clip change html", (hash, prev)) if hash == prev: #self.onSetStatusSlot(("data copied","good")) return preview = cgi.escape(text) #crashes with big data preview = self.truncateTextLines(preview) preview = self.anchorUrls(preview) html_file_name = "%s.json" % hash html_file_path = os.path.join(self.CONTAINER_DIR, html_file_name) with open(html_file_path, 'w') as html_file: html_and_text = json.dumps( {"html_and_text": { "html": html, "text": text }}) html_file.write(html_and_text) prepare = dict( file_names=[html_file_name], clip_display=preview, clip_type="html", ) elif mimeData.hasText() and not mimeData.hasUrls( ): #linux appears to provide text for files, so make sure it is not a file or else this will overrie it original = mimeData.text().encode("utf8") print original prev = self.previous_hash hash = format(hash128(original), "x") PRINT("on clip change text", (hash, prev)) if hash == prev: #self.onSetStatusSlot(("text copied","good")) return preview = cgi.escape( original) #prevent html from styling in qlabel preview = self.truncateTextLines(preview) preview = self.anchorUrls(preview) text_file_name = "%s.txt" % hash text_file_path = os.path.join(self.CONTAINER_DIR, text_file_name) with open(text_file_path, 'w') as text_file: text_file.write(original) prepare = dict( file_names=[text_file_name], clip_display=preview, clip_type="text", ) elif mimeData.hasUrls(): is_files = [] for each in mimeData.urls(): is_files.append(each.isLocalFile()) if not (is_files and all(is_files)): return PRINT("is files", True) os_file_paths_new = [] for each in self.clipboard.mimeData().urls(): #PRINT("path", each.toString().encode()) each_path = each.path()[( 1 if os.name == "nt" else 0 ):] #urls() returns /c://...// in windows, [1:] removes the starting /, not sure how this will affect *NIXs #if os.name=="nt": # each_path = each_path.encode(sys.getfilesystemencoding()) #windows uses mbcs encoding, not utf8 like *nix, so something like a chinese character will result in file operations raising WindowsErrors #http://stackoverflow.com/questions/10180765/open-file-with-a-unicode-filename standardized_path = os.path.abspath( each_path ) #abspath is needed to bypass symlinks in *NIX systems, also guarantees slashes are correct (C:\\...) for windows os_file_paths_new.append(standardized_path) os_file_paths_new.sort() try: os_file_sizes_new = map( lambda each_os_path: getFolderSize(each_os_path, max=self.MAX_FILE_SIZE) if os.path.isdir(each_os_path) else os.path.getsize( each_os_path), os_file_paths_new) except ZeroDivisionError: PRINT("failure", 213) return if sum(os_file_sizes_new) > self.MAX_FILE_SIZE: #self.sb.toggleStatusIcon(msg='Files not uploaded. Maximum files size is 50 megabytes.', icon="bad") self.onSetStatusSlot(("Files bigger than 50MB", "warn")) PRINT("failure", 218) return #upload error clip os_file_hashes_new = set([]) os_file_names_new = [] display_file_names = [] for each_path in os_file_paths_new: each_file_name = os.path.split(each_path)[1] os_file_names_new.append(each_file_name) if os.path.isdir(each_path): display_file_names.append(each_file_name + " (%s things inside)" % len(os.listdir(each_path)) + "._folder") os_folder_hashes = [] for dirName, subdirList, fileList in os.walk( each_path, topdown=False): #subdirList = filter(...) #filer out any temp or hidden folders for fname in fileList: if fname.upper( ) not in self.FILE_IGNORE_LIST: #DO NOT calculate hash for system files as they are always changing, and if a folder is in clipboard, a new upload may be initiated each time a system file is changed each_sub_path = os.path.join(dirName, fname) with open(each_sub_path, 'rb') as each_sub_file: each_relative_path = each_sub_path.split( each_path )[1] #c:/python27/lib/ - c:/python27/lib/bin/abc.pyc = bin/abc.pyc each_relative_hash = each_relative_path + hex( hash128(each_sub_file.read()) ) #WARNING- some files like thumbs.db constantly change, and therefore may cause an infinite upload loop. Need an ignore list. os_folder_hashes.append( each_relative_hash ) #use relative path+filename and hash so that set does not ignore two idenitcal files in different sub-directories. Why? let's say bin/abc.pyc and usr/abc.pyc are identical, without the aforementioned system, a folder with just bin/abc.pyc will yield same hash as bin/abc.pyc + usr/abc.pyc, not good. each_file_name = os.path.split(each_path)[1] os_folder_hashes.sort() each_data = "".join(os_folder_hashes) #whole folder hash else: #single file display_file_names.append(each_file_name) with open(each_path, 'rb') as each_file: each_file_name = os.path.split(each_path)[1] each_data = each_file.read() #update status os_file_hashes_new.add( hash128(each_file_name.encode("utf8")) + hash128(each_data) ) #http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames #append the hash for this file #use filename and hash so that set does not ignore copies of two idenitcal files (but different names) in different directories #also hash filename as this can be a security issue when stored serverside checksum = format(sum(os_file_hashes_new), "x") if self.previous_hash == checksum: #checks to make sure if name and file are the same PRINT("failure", 262) #self.onSetStatusSlot(("File%s copied" % ("s" if len(os_file_names_new) > 1 else "") , "good")) return else: hash = checksum #copy files to temp. this is needed for each_new_path in os_file_paths_new: try: if os.path.isdir(each_new_path): distutils.dir_util.copy_tree( each_new_path, os.path.join(self.CONTAINER_DIR, os.path.split(each_new_path)[1])) else: distutils.file_util.copy_file(each_new_path, self.CONTAINER_DIR) except distutils.errors.DistutilsFileError: #show error PRINT("failure", 274) pass #MUST PASS since file may already be there. prepare = dict( file_names=os_file_names_new, clip_display=display_file_names, clip_type="files", ) else: self.onSetStatusSlot(("Clipping is incompatible", "warn")) return prepare["hash"] = hash prepare[ "container_name"] = self.panel_stacked_widget.getMatchingContainerForHash( hash) async_process = dict(question="Update?", data=prepare) self.outgoingSignalForWorker.emit(async_process) self.previous_hash = hash
def exportGIFFromSequence(self, sequence, inFrame, outFrame, outputFilePath=None, dt=1.0 / 24.0): """ Exports a Sequence to a GIF over a range of in-outFrame. If no outputFilePath is specified, the GIF is written to the Desktop. dt sets the time between rendered frames """ duration = outFrame - inFrame if duration > 500: print "The mighty GIF cannot handle your duration of 500+ frames! Rendering only the first 500 frames" outFrame = inFrame + 499 # Images for GIF... if hasattr(sequence, 'thumbnail'): images = [] self.renderPreview.show() count = 1 for t in range(inFrame, outFrame): thumb = sequence.thumbnail(t) buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) thumb.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) images += [Image.open(strio)] progress = int(100.0 * (float(count) / float(duration))) hiero.core.log.debug('Progress is: ' + str(progress)) self.renderPreview.lbl.setPixmap(QtGui.QPixmap(thumb)) self.renderPreview.pbar.setValue(progress) QtCore.QCoreApplication.processEvents() count += 1 if not self.renderPreview.renderingEnabled: print 'Rendering Cancelled' self.renderPreview.hide() self.renderPreview.renderingEnabled = True return if not outputFilePath: try: outputFilePath = os.path.join(os.getenv('HOME'), 'Desktop', ('myGif_%i.gif' % time.time())) except: from os.path import expanduser outputFilePath = os.path.join(expanduser('~'), 'Desktop', ('myGif_%i.gif' % time.time())) writeGif(outputFilePath, images, duration=dt) self.renderPreview.hide() hiero.ui.openInOSShell(outputFilePath)