def exportThumbnail(self, report_path, thumbpath, name, node, size=None): self.thumbnailer = Thumbnailer() if self.thumbnailer.isThumbnailable(node): pixmap = self.thumbnailer.generate(node, iconSize=256, frames=10, blocking=True) self.thumbnailer.unregister() if pixmap: try: exportPath = os.path.join(report_path, os.path.join(thumbpath, name)) array = QByteArray() qfile = QBuffer(array) qfile.open(QIODevice.ReadWrite) pixmap.save(qfile, 'JPG') qfile.seek(0) with open(exportPath, 'wb') as f: f.write(qfile.read(qfile.size())) qfile.close() return True except Exception as e: qfile.close() return False else: return False
def xmlbuffer(self): queryimpl = QXmlQuery(QXmlQuery.XQuery10) #merge params from xquerynames and query path arguments params = copy.deepcopy(self.xquerynames) for name,value in self._queryparams.iteritems(): params.append([name,value]) #push values into external variable names in xquery for item in params: if len(item)==3 : # item has namespace (name,value,namespace) = item qname = QXmlName(queryimpl.namePool(), name, namespace) else: (name,value) = item qname = QXmlName(queryimpl.namePool(), name) qvalue = QXmlItem(value) queryimpl.bindVariable(qname,qvalue) #bind focus if available if(self.focuspath != None): queryimpl.setFocus(QUrl.fromLocalFile(self.focuspath)) queryimpl.setQuery(self.querysource) buf = QBuffer() buf.open(QBuffer.ReadWrite) queryimpl.evaluateTo(buf) buf.close() data = buf.data() return data
def __init__(self): QWidget.__init__(self) self.tray = Tray(self) self.setMinimumSize(QSize(320, 200)) self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setMargin(1) self.text = QTextBrowser(self) self.text.setReadOnly(True) self.text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text.setOpenExternalLinks(True) self.verticalLayout.addWidget(self.text) self.text.textChanged.connect(self.on_text_changed) self.notify = Notify(self) self.movie = QMovie() dev = QBuffer() dev.setData(QByteArray.fromBase64(CHECK_IMAGE)) dev.open(QBuffer.ReadOnly) dev.setParent(self.movie) self.movie.setDevice(dev) self.movie.frameChanged.connect(self.on_frame_changed) self.realized = False self.show()
def screenshot(self): logging.debug('screenshot() invoked') frame = self.page().mainFrame() size = frame.contentsSize() if (self.screenWidth): size.setWidth(self.screenWidth) if (self.screenHeight): size.setHeight(self.screenHeight) if (self.minWidth and self.minWidth > self.screenWidth): size.setWidth(self.minWidth) if (self.minHeight and self.minHeight > self.screenHeight): size.setHeight(self.minHeight) self.page().setViewportSize(size) image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() buffer = QBuffer() buffer.open(QIODevice.ReadWrite) image.save(buffer, self.format, self.quality) logging.debug('screenshot() returned image of type ' + self.content_type + ' of length ' + str(buffer.data().length())) return { 'content': buffer.data(), 'content_type': self.content_type }
def __init__(self): QWidget.__init__(self) self.tray = Tray(self) self.setMinimumSize(QSize(320, 200)) self.setWindowFlags(Qt.Popup|Qt.FramelessWindowHint) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setMargin(1) self.text = QTextBrowser(self) self.text.setReadOnly(True) self.text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text.setOpenExternalLinks(True) self.verticalLayout.addWidget(self.text) self.text.textChanged.connect(self.on_text_changed) self.notify = Notify(self) self.movie = QMovie() dev = QBuffer() dev.setData(QByteArray.fromBase64(CHECK_IMAGE)) dev.open(QBuffer.ReadOnly) dev.setParent(self.movie) self.movie.setDevice(dev) self.movie.frameChanged.connect(self.on_frame_changed) self.realized = False self.show()
def newfunc(): ba = QByteArray(data) # keep reference to avoid GC f = QBuffer(ba) f.open(mode) try: func(f) finally: f.close()
def from_QImage(self, img): buf = QByteArray() bf = QBuffer(buf) bf.open(QIODevice.WriteOnly) img.save(bf, format='PNG') self.buf = buf.data() self.format = PackedQImage.FORMAT_PNG self._encode()
def get_html_img(scene): """ Create HTML img element with base64-encoded image from the scene """ byte_array = QByteArray() filename = QBuffer(byte_array) filename.open(QIODevice.WriteOnly) PngFormat.write(filename, scene) img_encoded = byte_array.toBase64().data().decode("utf-8") return "<img src='data:image/png;base64,%s'/>" % img_encoded
def render_image(self): public_rect = self.live_text_rect() #global_rect = QtCore.QRect(self.mapToGlobal(public_rect.topLeft()), self.mapToGlobal(public_rect.bottomRight())) pixmap = QPixmap.grabWindow(self.win_id, public_rect.x() + 1, public_rect.y() + 1, 768, 576) buf = QBuffer() buf.open(QIODevice.WriteOnly) pixmap.save(buf, "JPG", 75) return buf.data()
def pixmap_to_imgformat(pixmap, format): import io from PyQt4.QtCore import QBuffer, QByteArray, QIODevice byte_array = QByteArray() buffer = QBuffer(byte_array) buffer.open(QIODevice.WriteOnly) pixmap.save(buffer, format) string_io = io.BytesIO(byte_array) string_io.seek(0) return string_io.read()
def getImage(self): """ Return the loaded image """ if self.isDefault: return None pix = self.orignalimage by = QByteArray() buf = QBuffer(by) buf.open(QIODevice.WriteOnly) pix.save(buf, "JPG") return by
def QIm2PIL(qimg): buff = QBuffer() buff.open(QIODevice.WriteOnly) qimg.save(buff, 'BMP') fp = StringIO() fp.write(buff.data()) buff.close() fp.seek(0) pilimg = Image.open(fp) if pilimg.mode == 'P': return pilimg.convert('L') return pilimg
def render_layers(layer_paths): """ :param layer_paths: A list of layer paths. :return: Buffer containing output. Note caller is responsible for closing the buffer with buffer.close() :rtype: QBuffer """ layers = [] extent = None crs = QgsCoordinateReferenceSystem() crs.createFromSrid(3857) for layer_path in layer_paths: map_layer = QgsVectorLayer(layer_path, None, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(map_layer) transform = QgsCoordinateTransform(map_layer.crs(), crs) print map_layer.extent().toString() layer_extent = transform.transform(map_layer.extent()) if extent is None: extent = layer_extent else: extent.combineExtentWith(layer_extent) print extent.toString() # set layer set layers.append(map_layer.id()) # add ID of every layer map_settings = QgsMapSettings() map_settings.setDestinationCrs(crs) map_settings.setCrsTransformEnabled(True) map_settings.setExtent(extent) map_settings.setOutputSize(QSize(1000, 1000)) map_settings.setLayers(layers) # job = QgsMapRendererParallelJob(settings) job = QgsMapRendererSequentialJob(map_settings) job.start() job.waitForFinished() image = job.renderedImage() # Save teh image to a buffer map_buffer = QBuffer() map_buffer.open(QIODevice.ReadWrite) image.save(map_buffer, "PNG") image.save('/tmp/test.png', 'png') # clean up QgsMapLayerRegistry.instance().removeAllMapLayers() return map_buffer
def saveTiles(self): if self.tiles is None: QMessageBox.warning(None, self.plugin.pluginName, self.tr("No tiles have been downloaded.")) return # Let the user choose the directory to save to directory = QFileDialog.getExistingDirectory(caption=self.tr("{}: Choose directory").format(self.layerDef.title)) if not directory: # User cancelled the directory selection return # Build the content of the .aux.xml file containing the projection info projection_string = (self.crs().toWkt()) pam_string = '<PAMDataset>\n' + \ '<SRS>{}</SRS>\n'.format(projection_string) + \ '</PAMDataset>' for tile in self.tiles.tiles.values(): # Figure out the file format extension reader = QImageReader() buffer = QBuffer() buffer.setData(tile.data) buffer.open(QIODevice.ReadOnly) extension = str(reader.imageFormat(buffer)) # Build the file name of the image file image_file_name = "{}-{}-{}.{}".format(tile.x, tile.y, tile.zoom, extension) image_file_path = join(directory, image_file_name) # Save the image file with open(image_file_path, 'wb') as image_file: image_file.write(tile.data) # Save the .aux.xml with open(image_file_path + '.aux.xml', 'w') as aux_file: aux_file.write(pam_string) # Save the world file containing the georeferencing information tile_rect = self.tiles.serviceInfo.getTileRect(tile.zoom, tile.x, tile.y) tile_size = self.tiles.TILE_SIZE with open(image_file_path + 'w', 'w') as world_file: world_file.writelines([ str(tile_rect.width() / tile_size) + '\n', '0\n', '0\n', str(-tile_rect.height() / tile_size) + '\n', str(tile_rect.xMinimum()) + '\n', str(tile_rect.yMaximum()) + '\n' ]) # Done msg = self.tr("Tiles have been saved.") self.showMessageBar(msg, QgsMessageBar.INFO, 2)
def _qimage_to_pil(self, qimage): """ Convert QImage to PIL Image """ ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) qimage.save(bf, 'TIFF', quality=100) bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) return PIL.Image.open(buf)
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): view_box = elem.get('viewBox', elem.get('viewbox', None)) sizes = None logger = self.oeb.logger if view_box is not None: try: box = [ float(x) for x in filter(None, re.split('[, ]', view_box)) ] sizes = [box[2] - box[0], box[3] - box[1]] except (TypeError, ValueError, IndexError): logger.warn( 'SVG image has invalid viewBox="%s", ignoring the viewBox' % view_box) else: for image in elem.xpath( 'descendant::*[local-name()="image" and ' '@height and contains(@height, "%")]'): logger.info( 'Found SVG image height in %, trying to convert...') try: h = float(image.get('height').replace('%', '')) / 100. image.set('height', str(h * sizes[1])) except: logger.exception( 'Failed to convert percentage height:', image.get('height')) data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() if size.width() == 100 and size.height() == 100 and sizes: size.setWidth(sizes[0]) size.setHeight(sizes[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)
def OCRperformOCRName(position,x,y,w,h,digits = False): img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h) #img.save('a.png', 'png') buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) im = Image.open(strio) pixdata = im.load(); for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (255, 255, 255) else: pixdata[x, y] = (0, 0, 0) #Add extra space on each side for y in xrange(im.size[1]): pixdata[0,y] = (255, 255, 255) pixdata[1,y] = (255, 255, 255) pixdata[im.size[0]-1,y] = (255, 255, 255) pixdata[im.size[0]-2,y] = (255, 255, 255) for x in xrange(im.size[0]): pixdata[x,0] = (255, 255, 255) pixdata[x,1] = (255, 255, 255) pixdata[x,im.size[1]-1] = (255, 255, 255) pixdata[x,im.size[1]-2] = (255, 255, 255) nx, ny = im.size im = im.resize((nx*5, ny*5), Image.ANTIALIAS) enh = ImageEnhance.Contrast(im) pixdata = im.load() for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR) rvalue = OCR_to_string(im,digits) #im.save("training"+str(position)+""+str(int(random.random()*10000)) +".png","PNG") return rvalue
def capture_image(session, selector=None, outformat="jpg"): """ capture page as image """ # do capture now cap = None if selector is not None: cap = session.capture(selector=selector) else: cap = session.capture() # create a buffered image buffer = QBuffer() buffer.open(QIODevice.ReadWrite) cap.save(buffer, 'JPG' if outformat.upper() in ('JPG', 'JPEG') else 'PNG') buffer.close() return buffer, 'image/' + 'jpeg' if outformat.upper() in ('JPG','JPEG') else 'png'
def capture_to_buf(self, selector=None): """capture the images of selector to StringIO @param selector: Css selector. @return: The StringIO list. """ images = self.capture(selector) result = [] for image in images: ba = QByteArray() buf = QBuffer(ba) buf.open(QIODevice.ReadWrite) image.save(buf, 'jpg') stream = StringIO(str(buf.buffer())) result.append(stream) return result
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): view_box = elem.get('viewBox', elem.get('viewbox', None)) sizes = None logger = self.oeb.logger if view_box is not None: try: box = [float(x) for x in filter(None, re.split('[, ]', view_box))] sizes = [box[2]-box[0], box[3] - box[1]] except (TypeError, ValueError, IndexError): logger.warn('SVG image has invalid viewBox="%s", ignoring the viewBox' % view_box) else: for image in elem.xpath('descendant::*[local-name()="image" and ' '@height and contains(@height, "%")]'): logger.info('Found SVG image height in %, trying to convert...') try: h = float(image.get('height').replace('%', ''))/100. image.set('height', str(h*sizes[1])) except: logger.exception('Failed to convert percentage height:', image.get('height')) data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() if size.width() == 100 and size.height() == 100 and sizes: size.setWidth(sizes[0]) size.setHeight(sizes[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)
def rasterize_external(self, elem, style, item, svgitem): width = style['width'] height = style['height'] width = (width / 72) * self.profile.dpi height = (height / 72) * self.profile.dpi data = QByteArray(str(svgitem)) svg = QSvgRenderer(data) size = svg.defaultSize() size.scale(width, height, Qt.KeepAspectRatio) key = (svgitem.href, size.width(), size.height()) if key in self.images: href = self.images[key] else: logger = self.oeb.logger logger.info('Rasterizing %r to %dx%d' % (svgitem.href, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, 'PNG') data = str(array) manifest = self.oeb.manifest href = os.path.splitext(svgitem.href)[0] + '.png' id, href = manifest.generate(svgitem.id, href) manifest.add(id, href, PNG_MIME, data=data) self.images[key] = href elem.tag = XHTML('img') for attr in elem.attrib: if attr not in KEEP_ATTRS: del elem.attrib[attr] elem.attrib['src'] = item.relhref(href) if elem.text: elem.attrib['alt'] = elem.text elem.text = None for child in elem: elem.remove(child)
def createRequest(self, op, request, outgoingData = None): """ Protected method to create a request. @param op the operation to be performed (QNetworkAccessManager.Operation) @param request reference to the request object (QNetworkRequest) @param outgoingData reference to an IODevice containing data to be sent (QIODevice) @return reference to the created reply object (QNetworkReply) """ if request.url().toString() == "pyrc:home": html = startPage_html pixmap = UI.PixmapCache.getPixmap("ericWeb32.png") imageBuffer = QBuffer() imageBuffer.open(QIODevice.ReadWrite) if pixmap.save(imageBuffer, "PNG"): html.replace("IMAGE_BINARY_DATA_HERE", QString(imageBuffer.buffer().toBase64())) return NetworkReply(request, html.toUtf8(), "text/html", self.parent()) return NetworkProtocolUnknownErrorReply("pyrc", self.parent())
def embed(im): """Converts a QImage or QPicture object into an ipython Image object for embedding into an ipython notebook. """ if isinstance(im, QPicture): pic = im im = QImage(im.width(), im.height(), QImage.Format_ARGB32_Premultiplied) p = QPainter() p.begin(im) p.drawPicture(0, 0, pic) p.end() w = QImageWriter() buf = QBuffer() buf.open(buf.WriteOnly) w.setFormat("png") w.setDevice(buf) w.write(im) return Image(data=str(buf.buffer()), format="png", embed=True)
def prepare(self): """ """ Logger.instance().debug("preparing plugin") # convert qicon to base64 pixmapIcon = self.pluginIcon.pixmap(64, 64, mode=QIcon.Normal, state=QIcon.Off) byteArray = QByteArray() buffer = QBuffer(byteArray) buffer.open(QIODevice.WriteOnly) pixmapIcon.save(buffer, "png", quality=100) iconBase64 = byteArray.toBase64().data() Logger.instance().debug("icon converted to base64") self.sendMessage(cmd='configure', data=str(iconBase64, 'utf8'), more={"description": self.pluginDescription})
class NodeThumbnailRenderReply(QNetworkReply): def __init__(self, parent, request): QNetworkReply.__init__(self, parent) self.qbuffer = None self.connect(self, SIGNAL('abouteToClose()'), self.__close) self.byteArray = QByteArray() self.qbuffer = QBuffer(self.byteArray) self.node = vfs().getnode(str(request.url().path().toUtf8())) self.thumbnailer = Thumbnailer() self.connect(self.thumbnailer, SIGNAL("ThumbnailUpdate"), self.updateThumbnail) self.setRequest(request) self.setOperation(QNetworkAccessManager.GetOperation) mime = "image/jpg" self.setHeader(QNetworkRequest.ContentTypeHeader, QVariant(mime)) self.open() self.setUrl(request.url()) self.connect(parent, SIGNAL("ready"), self.ready) self.ready() def ready(self): if self.node.dataType().find('video') != -1: pixmap = self.thumbnailer.generate(self.node, iconSize=128, frames=10) else: pixmap = self.thumbnailer.generate(self.node, iconSize=256, frames=10) if pixmap: self.updateThumbnail(self.node, pixmap) 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 abort(self): self.close() def __del__(self): self.thumbnailer.unregister() def open(self, mode=None): try: self.qbuffer.open(QIODevice.ReadWrite | QIODevice.Unbuffered) self.setOpenMode(QIODevice.ReadWrite | QIODevice.Unbuffered) return True except (AttributeError, IOError): return False def seek(self, pos): if self.qbuffer: return self.qbuffer.seek(pos) return False def __close(self): if self.qbuffer: self.qbuffer.close() self.qbuffer = None return True def readData(self, size): if self.qbuffer: return self.qbuffer.read(size) return "" def pos(self): if self.qbuffer: return self.qbuffer.pos() return 0 def isSequential(self): if self.qbuffer: return self.qbuffer.isSequential() return False def size(self): return self.qbuffer.size() def reset(self): if self.qbuffer: self.qbuffer.seek(0) return True return False def atEnd(self): if self.qbuffer: return self.qbuffer.atEnd() return False
def send(self, method, url, headers, body, context = None): qurl = QUrl.fromEncoded(url) request = QNetworkRequest() request.setUrl(qurl) method = self.translate_method(method, request) host, useragent, content_type = None, None, None for name, value in headers.items(): lname = name.lower() if 'user-agent' == lname: useragent = value elif 'host' == lname: host = value elif 'content-type' == lname: content_type = value elif 'content-length' == lname: continue request.setRawHeader(name, value) if not host: request.setRawHeader('Host', str(qurl.host())) if not useragent: request.setRawHeader('User-Agent', self.framework.useragent()) if 'POST' == method and not content_type: request.setRawHeader('Content-Type', 'application/x-www-form-urlencoded') if not body: if method in ('POST', 'PUT', 'CUSTOM'): # TODO: determine specific methods that expect content? body = '' else: device = None if method in ('GET', 'HEAD', 'DELETE'): # can't have body, because not supported by Qt network logic body = None device = None if body is not None: request.setRawHeader('Content-Length', str(len(body))) data = QByteArray(body) device = QBuffer(self) device.setData(data) device.open(QIODevice.ReadOnly) request.setAttribute(request.CacheLoadControlAttribute, request.AlwaysNetwork) if 'GET' == method: reply = self.networkAccessManager.get(request) elif 'HEAD' == method: reply = self.networkAccessManager.head(request) elif 'DELETE' == method: reply = self.networkAccessManager.head(request) elif 'POST' == method: reply = self.networkAccessManager.post(request, device) elif 'PUT' == method: reply = self.networkAccessManager.put(request, device) else: reply = self.networkAccessManager.sendCustomRequest(request, method, device) response = NetworkResponse(self.framework, self.callback, reply, context, self) return NetworkRequest(request, reply, response, context, self)
img = QImage(iwidth, iheight, QImage.Format_RGB32) img.setDotsPerMeterX(dpi / 25.4 * 1000) img.setDotsPerMeterY(dpi / 25.4 * 1000) img.fill(qRgb(255, 255, 255)) dpi = img.logicalDpiX() print("Image DPI: %d" % dpi) render.setOutputSize(QSize(img.width(), img.height()), dpi) render.setDestinationCrs(crs) render.setProjectionsEnabled(True) render.setMapUnits(crs.mapUnits()) render.setExtent(extent) print("Scale: %f" % render.scale()) painter = QPainter(img) painter.setRenderHint(QPainter.Antialiasing) render.render(painter) painter.end() ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() with open(args.output, 'wb') as fd: fd.write(ba)
def do_GET(self): try: self.path = re.sub('[^.a-zA-Z0-9]', "", str(self.path)) if self.path == "" or self.path == None or self.path[:1] == ".": self.send_error(403, 'Forbidden') if self.path.endswith(".html"): directory = os.path.dirname(os.path.abspath(__file__)) data = open(os.path.join(directory, self.path), "rb").read() self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(data) elif self.path.endswith(".mjpeg"): self.thread = thread = OSCThread(self.server.args) thread.daemon = True thread.start() actor_names = ["merle", "uwe", "bjoern"] num_data = 100 colors = ["r", "g", "b"] qtapp = QtGui.QApplication([]) plotter = EkgPlot(actor_names, num_data, colors) self.send_response(200) self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--2342") self.end_headers() event_loop = QtCore.QEventLoop() last_frame = time.time() - 1.0 frame_rate = 13.0 frame_length = 1. / frame_rate plotter.new_round() while 1: event_loop.processEvents() qtapp.sendPostedEvents(None, 0) while 1: try: osc_address, args = queue.get_nowait() plotter.update(osc_address, args[0]) except Queue.Empty: break now = time.time() delta = now - last_frame if delta > frame_length: plotter.update_missing_actors() plotter.render() exporter = pg.exporters.ImageExporter.ImageExporter( plotter.plot.plotItem) exporter.parameters()['width'] = 768 img = exporter.export(toBytes=True) buffer = QBuffer() buffer.open(QIODevice.WriteOnly) img.save(buffer, "JPG") JpegData = buffer.data() self.wfile.write( "--2342\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData)) last_frame = now plotter.new_round() #JpegData = None #buffer = None #img = None #exporter = None time.sleep(0.01) except (KeyboardInterrupt, SystemError), e: raise e
def renderer(self): if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ: os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp' qgis = None while True: options, result = self.queue.get() # Don't start QGIS until first request if qgis is None: qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setDefaultSvgPaths(qgis.svgPaths() + self.settings.get('svgpaths')) qgis.setMaxThreads(1) qgis.initQgis() try: if isinstance(options, LegendOptions): style, = options layer = self._qgs_memory_layer(style) layer.setName(style.parent.display_name) QgsMapLayerRegistry.instance().addMapLayer(layer) root = QgsLayerTreeGroup() root.addLayer(layer) # 'Cannot create a QPixmap when no GUI is being used' # warning occurs here model = QgsLayerTreeModel(root) settings = QgsLegendSettings() settings.setTitle('') settings.setBoxSpace(1) settings.setSymbolSize(QSizeF(5, 3)) settings.setDpi(96) renderer = QgsLegendRenderer(model, settings) # Dots per mm dpmm = settings.dpi() / 25.4 min_size = renderer.minimumSize() size = QSize(dpmm * min_size.width(), dpmm * min_size.height()) img = QImage(size, QImage.Format_ARGB32) img.fill(QColor(0, 0, 0, 0)) painter = QPainter() painter.begin(img) painter.scale(dpmm, dpmm) renderer.drawLegend(painter) painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) result.put(buf) else: path = features = None if isinstance(options, VectorRenderOptions): style, features, render_size, \ extended, target_box = options layer = self._qgs_memory_layer(style, features=features) elif isinstance(options, RasterRenderOptions): style, path, render_size, \ extended, target_box = options layer = QgsRasterLayer(path) layer.loadNamedStyle( self.env.file_storage.filename(style.qml_fileobj)) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(layer.crs()) settings.setMapUnits(layer.crs().mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Create QImage by hand to be able to use # QgsMapRendererCustomPainterJob. Others will not # allow to workaround a bug with overlay rendering. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # These cludges are needed for rendering # on transparent background, otherwise it's a mess. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI should be equal to settings, otherwise an error. # In QImage the resolution is set in dots per meter # for each axis. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() img = self._qimage_to_pil(img) # Clip needed part result.put(img.crop(target_box)) # Cleanup if path is not None: gdal.Unlink(path) except Exception as exc: self.logger.error(exc.message) result.put(exc) qgis.exitQgis()
def render(self, params): self.check_required_params(params) with change_directory(self.project_root): crs = QgsCoordinateReferenceSystem() crs.createFromSrid(params.get('srs')) img = QImage( QSize(*params.get('image_size')), QImage.Format_ARGB32_Premultiplied ) dpm = 1 / 0.00028 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) # set background color bgcolor = params.get('bgcolor') if params.get('transparent'): # fully transparent bgcolor.append(0) else: # fully opaque bgcolor.append(255) color = QColor(*bgcolor) img.fill(color) map_settings = QgsMapSettings() map_settings.setBackgroundColor(color) map_settings.setDestinationCrs(crs) map_settings.setCrsTransformEnabled(True) map_settings.setExtent(QgsRectangle(*params.get('bbox'))) map_settings.setOutputDpi(img.logicalDpiX()) map_settings.setOutputSize(img.size()) map_settings.setMapUnits(crs.mapUnits()) layers = params.get('layers') self.setTransparencies(layers, params.get('transparencies')) map_settings.setLayers(layers) p = QPainter() p.begin(img) job = QgsMapRendererCustomPainterJob(map_settings, p) job.start() job.waitForFinished() map_buffer = QBuffer() map_buffer.open(QIODevice.ReadWrite) if params.get('image_format') == 'jpeg': img.save(map_buffer, 'JPEG') elif params.get('image_format') == 'png8': png8 = img.convertToFormat(QImage.Format_Indexed8) png8.save(map_buffer, "PNG") else: img.save(map_buffer, 'PNG') # clean up p.end() map_buffer.close() return map_buffer.data()
def base64image(image): ba = QByteArray() buffer = QBuffer(ba) buffer.open(QIODevice.WriteOnly) image.save(buffer, "PNG") return "data:image/png;base64," + ba.toBase64().data()
def renderer(self): qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setMaxThreads(1) qgis.initQgis() while True: try: fndata, srs, render_size, extended, \ target_box, result = self.queue.get() layer = QgsVectorLayer(fndata, 'layer', 'ogr') crs = QgsCoordinateReferenceSystem(srs.id) layer.setCrs(crs) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(crs) settings.setMapUnits(crs.mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Создаем QImage руками чтобы можно было использовать # QgsMapRendererCustomPainterJob. Остальные не позволяют # обойти баг с рисованием поверх старого. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # Эти костыли нужны для того, чтобы корректно рисовались # слои на прозрачном фоне, без этого получается каша. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI должно быть таким же как в settings, иначе ошибка. В QImage # разрешение указывается в точках на метр по каждой оси. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() # Преобразование QImage в PIL ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) img = PIL.Image.open(buf) # Вырезаем нужный нам кусок изображения result.put(img.crop(target_box)) except Exception as e: self.logger.error(e.message) qgis.exitQgis()
def getLegendGraphic(self, params): qgsLayer = self.layerRegistry.mapLayer(params.get('layer')) boxSpace = 1 layerSpace = 2 # layerTitleSpace = 3 symbolSpace = 2 iconLabelSpace = 2 symbolWidth = 5 symbolHeight = 3 drawLegendLabel = True rootGroup = QgsLayerTreeGroup() rootGroup.addLayer(qgsLayer) # layer = QgsLayerTreeLayer(qgsLayer) # if qgsLayer.title(): # layer.setLayerName(qgsLayer.title()) legendModel = QgsLayerTreeModel(rootGroup) rootChildren = rootGroup.children() img_tmp = QImage(QSize(1, 1), QImage.Format_ARGB32_Premultiplied) dpm = 1 / 0.00028 img_tmp.setDotsPerMeterX(dpm) img_tmp.setDotsPerMeterY(dpm) dpmm = img_tmp.dotsPerMeterX() / 1000.0 del img_tmp legendSettings = QgsLegendSettings() legendSettings.setTitle('') legendSettings.setBoxSpace(boxSpace) legendSettings.rstyle(QgsComposerLegendStyle.Subgroup).setMargin(QgsComposerLegendStyle.Top, layerSpace) legendSettings.rstyle(QgsComposerLegendStyle.Symbol).setMargin(QgsComposerLegendStyle.Top, symbolSpace) legendSettings.rstyle(QgsComposerLegendStyle.SymbolLabel).setMargin(QgsComposerLegendStyle.Left, iconLabelSpace) legendSettings.setSymbolSize(QSizeF(symbolWidth, symbolHeight)) # legendSettings.rstyle(QgsComposerLegendStyle.Subgroup).setFont(layerFont) # legendSettings.rstyle(QgsComposerLegendStyle.SymbolLabel).setFont(itemFont) # // TODO: not available: layer font color # legendSettings.setFontColor( itemFontColor ); # for node in rootChildren: # if (QgsLayerTree.isLayer(node)): # QgsLegendRenderer.setNodeLegendStyle(node, QgsComposerLegendStyle.Subgroup) # # rule item titles # # if ( !mDrawLegendItemLabel ) # # for legendNode in legendModel.layerLegendNodes(nodeLayer): # # legendNode.setUserLabel(' ') # # } legendRenderer = QgsLegendRenderer(legendModel, legendSettings) minSize = legendRenderer.minimumSize() s = QSize(minSize.width() * dpmm, minSize.height() * dpmm) img = QImage(s, QImage.Format_ARGB32_Premultiplied) # fill in the background color = QColor(0, 0, 0, 0) img.fill(color) p = QPainter() p.begin(img) p.setRenderHint(QPainter.Antialiasing, True) p.scale(dpmm, dpmm) legendRenderer.drawLegend(p) map_buffer = QBuffer() map_buffer.open(QIODevice.ReadWrite) img.save(map_buffer, 'PNG') # clean up map_buffer.close() p.end() # self.layerRegistry.removeAllMapLayers() return map_buffer.data()
class ReportJSRenderReply(QNetworkReply): def __init__(self, parent, request): QNetworkReply.__init__(self, parent) self.__parent = parent self.qbuffer = None self.connect(self, SIGNAL('abouteToClose()'), self.__close) self.byteArray = QByteArray() self.qbuffer = QBuffer(self.byteArray) self.setRequest(request) self.setOperation(QNetworkAccessManager.GetOperation) self.setHeader( QNetworkRequest.ContentTypeHeader, QVariant( '"text/javascript" charset="utf-8" language="javascript"')) self.setAttribute(QNetworkRequest.CacheLoadControlAttribute, QVariant(QNetworkRequest.AlwaysNetwork)) self.open() self.setUrl(request.url()) self.writeJS() QTimer.singleShot(0, self, SIGNAL("readyRead()")) QTimer.singleShot(0, self, SIGNAL("finished()")) def writeJS(self): pageName = self.url().path() pageName = unicode(pageName).encode('UTF-8', 'replace') buff = "" try: buff = self.__parent.pages[pageName] except KeyError: print "can't get page " + pageName self.qbuffer.write(buff) self.qbuffer.seek(0) def abort(self): self.close() def __del__(self): pass def open(self, mode=None): try: self.qbuffer.open(QIODevice.ReadWrite | QIODevice.Unbuffered) self.setOpenMode(QIODevice.ReadWrite | QIODevice.Unbuffered) return True except (AttributeError, IOError): return False def seek(self, pos): if self.qbuffer: return self.qbuffer.seek(pos) return False def __close(self): if self.qbuffer: self.qbuffer.close() self.qbuffer = None return True def readData(self, size): if self.qbuffer: return self.qbuffer.read(size) return "" def pos(self): if self.qbuffer: return self.qbuffer.pos() return 0 def isSequential(self): if self.qbuffer: return self.qbuffer.isSequential() return False def size(self): return self.qbuffer.size() def reset(self): if self.qbuffer: self.qbuffer.seek(0) return True return False def atEnd(self): if self.qbuffer: return self.qbuffer.atEnd() return False
def do_GET(self): self.thread = thread = OSCThread() thread.daemon = True thread.start() actors = list() is_item1 = True is_item2 = True is_item3 = True def setPositions(): for ix, item in enumerate(actors): item.setPos(0, ix * 6) def scale_data(data, ix, max_items): scale = 254 / max_items * ix return [value / max_items + scale for value in data] try: self.path = re.sub('[^.a-zA-Z0-9]', "", str(self.path)) if self.path == "" or self.path == None or self.path[:1] == ".": return if self.path.endswith(".html"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() elif self.path.endswith(".mjpeg"): data_points = 1000 self.send_response(200) plot_data1 = data = deque([0] * data_points) plot_data2 = data = deque([0] * data_points) plot_data3 = data = deque([0] * data_points) plt = PlotWidget(title="<h1>EKG</h1>", name="Merle") plt.hide() plotItem1 = pg.PlotCurveItem(pen=pg.mkPen('r', width=2), name="bjoern") plotItem2 = pg.PlotCurveItem(pen=pg.mkPen('g', width=2), name="merle") plotItem3 = pg.PlotCurveItem(pen=pg.mkPen('b', width=2), name="uwe") print type(plotItem1) pen = pg.mkPen(254, 254, 254) plotItem1.setShadowPen(pen=pen, width=6, cosmetic=True) plotItem2.setShadowPen(pen=pen, width=6, cosmetic=True) plotItem3.setShadowPen(pen=pen, width=6, cosmetic=True) actors.append(plotItem1) actors.append(plotItem2) actors.append(plotItem3) plotItem1.setPos(0, 0 * 6) plotItem2.setPos(0, 1 * 6) plotItem3.setPos(0, 2 * 6) plt.addItem(plotItem1) plt.addItem(plotItem2) plt.addItem(plotItem3) plt.setLabel('left', "<h2>Amplitude</h2>") plt.setLabel('bottom', "<h2>Time</h2>") plt.showGrid(True, True) ba = plt.getAxis("bottom") bl = plt.getAxis("left") ba.setTicks([]) bl.setTicks([]) plt.setYRange(0, 254) self.wfile.write( "Content-Type: multipart/x-mixed-replace; boundary=--aaboundary" ) self.wfile.write("\r\n\r\n") plt.resize(1280, 720) while 1: while 1: try: osc_address, args = queue.get_nowait() except Queue.Empty: break value = args[0] if osc_address == "/bjoern/ekg": plot_data1.append(value) plot_data1.popleft() try: plotItem1.setData(y=np.array( scale_data(plot_data1, actors.index(plotItem1), len(actors))), clear=True) except ValueError: pass elif osc_address == "/merle/ekg": plot_data2.append(value) plot_data2.popleft() try: plotItem2.setData(y=np.array( scale_data(plot_data2, actors.index(plotItem2), len(actors))), clear=True) except ValueError: pass elif osc_address == "/uwe/ekg": plot_data3.append(value) plot_data3.popleft() try: plotItem3.setData(y=np.array( scale_data(plot_data3, actors.index(plotItem3), len(actors))), clear=True) except ValueError: pass elif osc_address == "/plot/uwe": if value == 1 and is_item3 == False: print "uwe on" plt.addItem(plotItem3) is_item3 = True actors.append(plotItem3) setPositions() elif value == 0 and is_item3 == True: print "uwe off" plt.removeItem(plotItem3) is_item3 = False actors.remove(plotItem3) setPositions() elif osc_address == "/plot/merle": if value == 1 and is_item2 == False: print "merle on" plt.addItem(plotItem2) is_item2 = True actors.append(plotItem2) setPositions() elif value == 0 and is_item2 == True: print "merle off" plt.removeItem(plotItem2) is_item2 = False actors.remove(plotItem2) setPositions() elif osc_address == "/plot/bjoern": if value == 1 and is_item1 == False: print "bjoern on" plt.addItem(plotItem1) is_item1 = True actors.append(plotItem1) setPositions() elif value == 0 and is_item1 == True: print "bjoern off" plt.removeItem(plotItem1) is_item1 = False actors.remove(plotItem1) setPositions() exporter = pg.exporters.ImageExporter.ImageExporter( plt.plotItem) img = exporter.export("tmpfile", True) buffer = QBuffer() buffer.open(QIODevice.WriteOnly) img.save(buffer, "JPG", 100) JpegData = buffer.data() del buffer self.wfile.write( "--aaboundary\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData)) elif self.path.endswith(".jpeg"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'image/jpeg') self.end_headers() self.wfile.write(f.read()) f.close() return except (KeyboardInterrupt, SystemError): thread.running = False thread.join() except IOError: self.send_error(404, 'File Not Found: %s' % self.path)
def buildXmlTree(self): """ Erzeugt den Element-Baum, der später in eine XML-Datei geschrieben werden kann. """ root = etree.Element(Config.PROGRAM_NAME, version=Config.version()) etree.SubElement(root, "species").text = self.__character.species etree.SubElement(root, "era").text = self.__character.era ## Identität identities = etree.SubElement(root, "identities") forenames = " ".join(self.__character.identity.forenames) etree.SubElement(identities, "identity", forenames=forenames, surname=self.__character.identity.surname, honorname=self.__character.identity.honorname, nickname=self.__character.identity.nickname, supername=self.__character.identity.supername, gender=self.__character.identity.gender, ) ## Daten etree.SubElement(root, "dates", birth=self.__character.dateBirth.toString(Config.DATE_FORMAT), becoming=self.__character.dateBecoming.toString(Config.DATE_FORMAT), game=self.__character.dateGame.toString(Config.DATE_FORMAT), ) etree.SubElement(root, "virtue").text = self.__character.virtue etree.SubElement(root, "vice").text = self.__character.vice breedElement = etree.SubElement(root, "breed") breedElement.text = self.__character.breed if self.__character.bonus: breedElement.attrib["bonusType"] = self.__character.bonus["type"] breedElement.attrib["bonusName"] = self.__character.bonus["name"] if "specialty" in self.__character.bonus: breedElement.attrib["bonusSpecialty"] = self.__character.bonus["specialty"] if self.__character.species == "Changeling": breedElement.attrib["kith"] = self.__character.kith etree.SubElement(root, "faction").text = self.__character.faction etree.SubElement(root, "organisation").text = self.__character.organisation etree.SubElement(root, "party").text = self.__character.party etree.SubElement(root, "height").text = str(self.__character.height) etree.SubElement(root, "weight").text = str(self.__character.weight) etree.SubElement(root, "eyes").text = self.__character.eyes etree.SubElement(root, "hair").text = self.__character.hair etree.SubElement(root, "nationality").text = self.__character.nationality etree.SubElement(root, "description").text = self.__character.description etree.SubElement(root, "powerstat").text = str(self.__character.powerstat) etree.SubElement(root, "morality").text = str(self.__character.morality) ## Geistesstörungen derangements = etree.SubElement(root, "derangements") for item in self.__character.derangements.items(): if item[1]: etree.SubElement(derangements, "derangement", morality=str(item[0])).text = item[1] ## Eigenschaften traits = etree.SubElement(root, "Traits") for item in self.__character.traits: traitTypeExists = False traitType = None for subitem in self.__character.traits[item]: traitCategoryExists = False traitCategory = None for subsubitem in self.__character.traits[item][subitem].values(): ## Eigenschaften müssen nur dann gespeichert werden, wenn ihr Wert != 0 ist und sie für die aktuell gewählte Spezies zur Verfügung stehen. if ( subsubitem.value != 0 and (not subsubitem.species or subsubitem.species == self.__character.species) ): if not traitTypeExists: traitType = etree.SubElement(traits, "Type", name=item) traitTypeExists = True if not traitCategoryExists: traitCategory = etree.SubElement(traitType, "Category", name=subitem) traitCategoryExists = True trait = etree.SubElement(traitCategory, "trait", name=subsubitem.name, value=str(subsubitem.value), ) # Zusatztext if item != "Subpower" and subsubitem.custom: trait.attrib["customText"] = str( subsubitem.customText ) # Spezialisierungen if subsubitem.specialties: etree.SubElement(trait, "specialties").text = Config.XML_SEPARATION_SYMBOL.join( str(n) for n in subsubitem.specialties ) ## Gegenstände items = etree.SubElement(root, "Items") if self.__character.weapons: weapons = etree.SubElement(items, "Weapons") for category in self.__character.weapons: weaponCategory = etree.SubElement(weapons, "Category", name=category) for weapon in self.__character.weapons[category]: etree.SubElement(weaponCategory, "weapon").text = weapon if self.__character.armor: etree.SubElement(items, "armor", dedicated=str(self.__character.armor["dedicated"])).text = self.__character.armor["name"] if self.__character.equipment or self.__character.magicalTool: equipment = etree.SubElement(items, "Equipment") for item in self.__character.equipment: etree.SubElement(equipment, "equipment").text = item if self.__character.magicalTool: etree.SubElement(equipment, "magicalTool").text = self.__character.magicalTool if self.__character.automobiles: automobiles = etree.SubElement(items, "Automobiles") for typ in self.__character.automobiles: itemType = etree.SubElement(automobiles, "Type", name=typ) for automobile in self.__character.automobiles[typ]: etree.SubElement(itemType, "item").text = automobile if self.__character.extraordinaryItems: extraordinaries = etree.SubElement(items, "ExtraordinaryItems") for typ in self.__character.extraordinaryItems: itemType = etree.SubElement(extraordinaries, "Type", name=typ) for extraordinaryItem in self.__character.extraordinaryItems[typ]: etree.SubElement(itemType, "item").text = extraordinaryItem ## Spezialseigenschaften der Spezies if self.__character.nimbus: etree.SubElement(root, "nimbus").text = self.__character.nimbus if self.__character.paradoxMarks: etree.SubElement(root, "paradoxMarks").text = self.__character.paradoxMarks if any((x.name and x.value > 0) for x in self.__character.vinculi): vinculi = etree.SubElement(root, "vinculi") for item in self.__character.vinculi: if item.name and item.value > 0: etree.SubElement(vinculi, "vinculum", value=str(item.value)).text = item.name companion = etree.SubElement( root, "companion", name = self.__character.companionName, power = str(self.__character.companionPower), finesse = str(self.__character.companionFinesse), resistance = str(self.__character.companionResistance), size = str(self.__character.companionSize), speedFactor = str(self.__character.companionSpeedFactor), ) for item in self.__character.companionNumina: etree.SubElement(companion, "numen").text = item for item in self.__character.companionInfluences: if item.name and item.value > 0: etree.SubElement(companion, "influence", value=str(item.value)).text = item.name if self.__character.companionBan: etree.SubElement(companion, "ban").text = self.__character.companionBan if self.__character.picture: imageData = QByteArray() imageBuffer = QBuffer(imageData) imageBuffer.open(QIODevice.WriteOnly) self.__character.picture.save(imageBuffer, Config.CHARACTER_PIC_FORMAT) # Schreibt das Bild in ein QByteArray im angegebenen Bildformat. imageData = imageData.toBase64().data() etree.SubElement(root, "picture").text = imageData.decode("UTF-8") return root
def OCRperformOCRDigit(x,y,w,h): rvalue = '' img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h) img.save('test.png', 'png') buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) im = Image.open(strio) #im = Image.open('/home/liutauras/Documents/Python/test.png') pixdata = im.load(); for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 550: pixdata[x, y] = (255, 255, 255) else: pixdata[x, y] = (0, 0, 0) #Add extra space on each side for y in xrange(im.size[1]): pixdata[0,y] = (255, 255, 255) pixdata[1,y] = (255, 255, 255) pixdata[im.size[0]-1,y] = (255, 255, 255) pixdata[im.size[0]-2,y] = (255, 255, 255) for x in xrange(im.size[0]): pixdata[x,0] = (255, 255, 255) pixdata[x,1] = (255, 255, 255) pixdata[x,im.size[1]-1] = (255, 255, 255) pixdata[x,im.size[1]-2] = (255, 255, 255) nx, ny = im.size im = im.resize((nx*5, ny*5), Image.ANTIALIAS) enh = ImageEnhance.Contrast(im) pixdata = im.load() for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR) #rvalue = OCR_to_string(im,True) pixdata = im.load() #Correct 4 not to overlap lastTot2 = 0 lastTot = 0; for x in xrange(im.size[0]): total = 0 for y in xrange(26,im.size[1]): total = total + sum(pixdata[x, y]) if(total == 20655 and lastTot == 20655 and lastTot2 == 9180): x = x - 1 for xT in range(x,3+x): for y in xrange(25,43): pixdata[xT,y] = (270,270,270) for xT in range(x,6+x): for y in xrange(35,40): pixdata[xT,y] = (270,270,270) lastTot2 = lastTot lastTot = total #Spit by Character totalSumLast = 0 startX = 0 for x in xrange(im.size[0]): #Start of digits flag totalSum = 0 for y in xrange(im.size[1]): totalSum = totalSum + pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if(totalSum < totalSumLast and totalSumLast == 45900): startX = x for y in xrange(im.size[1]): pixdata[x, y] = (0, 0, 0) elif(totalSum > totalSumLast and totalSum == 45900 and startX != 0): #Detect start on y axis startY = 0 for y1 in xrange(im.size[1]): innerSum = 0 divTot = 0 for x1 in xrange(startX,x): innerSum = innerSum + sum(pixdata[x1, y1]) divTot = divTot + 1 innerSum = innerSum/divTot if(startY == 0 and innerSum < 630): startY = y1 elif(startY != 0 and innerSum > 630): for x1 in xrange(startX,x): pixdata[x1, startY] = (0, 200, 0) pixdata[x1, y1] = (0, 0, 200) #Total area sum totalAreaSum = 0 for x1 in xrange(startX,x): for y2 in xrange(startY,y1): totalAreaSum = totalAreaSum + sum(pixdata[x1, y2]) #Decoding digit if(totalAreaSum == 190060): rvalue = rvalue + '1' elif(totalAreaSum == 8285): rvalue = rvalue + '.' elif(totalAreaSum == 231605 or totalAreaSum == 237725): rvalue = rvalue + '4' elif(totalAreaSum == 283625): rvalue = rvalue + '2' elif(totalAreaSum == 245375): rvalue = rvalue + '5' elif(totalAreaSum == 321875): rvalue = rvalue + '7' elif(totalAreaSum == 251495): rvalue = rvalue + '9' elif(totalAreaSum == 228545): rvalue = rvalue + '0' elif(totalAreaSum == 275975): rvalue = rvalue + '3' elif(totalAreaSum == 262970): rvalue = rvalue + '6' elif(totalAreaSum == 217070): rvalue = rvalue + '8' elif(totalAreaSum == 236195): rvalue = rvalue + '0' elif(totalAreaSum == 223190): rvalue = rvalue + '8' elif(totalAreaSum == 270620): rvalue = rvalue + '6' else: print '-------------------------' subprocess.call(['/usr/bin/canberra-gtk-play','--id','bell']) rvalue = rvalue + '' filename = 'errorB'+rvalue+'|'+str(totalAreaSum)+'|'+str(random.randint(1,1000))+'.png' print '--------E---------------' img.save(filename, 'png') print filename,totalAreaSum print '-------------------------' #print totalAreaSum startY = 0 startX = 0 for y in xrange(im.size[1]): pixdata[x, y] = (200, 0, 0) totalSumLast = totalSum #rvalue = '0'+rvalue rvalue = rvalue.replace('\n','').replace(' ','') if(len(rvalue) > 0): im.save("a.png") rvalue = rvalue.replace(',','').replace(' ','').replace('.','') rvalue = int(rvalue) else: rvalue = 0 return rvalue
class Connection(QTcpSocket): """Abstracts server-client connections. Whenever data is received, a Connection attempts to parse a Message and arguments from the data, and emits messageReceived for each parsed message. See QTcpSocket documentation for other members.""" messageSent = pyqtSignal(int, list) """Emitted whenever a message is sent. Arguments: the message type, list of arguments.""" messageReceived = pyqtSignal(int, list) """Emitted whenever a message is recieved. Arguments: the message type, list of arguments.""" messageReceived2 = pyqtSignal() def __init__(self, id = None, client = False, parent = None): """Creates a connection. id -- Optional socket descriptor. client -- Whether this connection is opened from the client side or server side. parent -- Parent object.""" QTcpSocket.__init__(self, parent) if id: if not self.setSocketDescriptor(id): self.done() return self.id = id self.player = None self.client = client self.buffer = QBuffer() self.buffer.open(QBuffer.ReadWrite) self.readyRead.connect(self._readIncomingData) def abort(self): """Aborts the connection.""" super(Connection, self).abort() def _readIncomingData(self): bytesWritten = self.buffer.write(self.readAll()) self.buffer.seek(0) result = self._parse() bytesRead = 0 while result: bytesRead += result[2] msg, args = result[:2] if self.client: log.debug("Received %s %s", msg, args) elif self.player and self.player.name: log.debug("Received %s %s from %s", msg, args, self.player) else: log.debug("Received %s %s from %s", msg, args, self.peerAddress().toString()) self.messageReceived.emit(msg, args) self.messageReceived2.emit() result = self._parse() #remove the successfully parsed data size = self.buffer.size() self.buffer.close() data = self.buffer.data() self.buffer.setData(data.right(size - bytesRead)) self.buffer.open(QBuffer.ReadWrite) self.buffer.seek(self.buffer.size()) def _parse(self): if self.buffer.bytesAvailable() >= 4: stream = QDataStream(self.buffer) msg = Message.fromInt(stream.readInt32()) if msg == None: return args = [] bytesRead = 4 for aType in msg.argTypes: if aType == str: if self.buffer.bytesAvailable() < 4: return length = stream.readInt32() if self.buffer.bytesAvailable() < length: return args.append(stream.readRawData(length)) bytesRead += 4 + length elif aType == int: if self.buffer.bytesAvailable() < 4: return args.append(stream.readInt32()) bytesRead += 4 elif aType == long: if self.buffer.bytesAvailable() < 8: return args.append(stream.readInt64()) bytesRead += 8 return (msg, args, bytesRead) def sendMessage(self, msg, args, id = None): """Sends a message. msg -- The message type. args -- List of message arguments. id -- An optional socket descriptor. If specified, then the message will only be sent if this connection's socket descriptor matches id.""" if id: if self.socketDescriptor() != id: return msg = Message.fromInt(msg) if not msg.validateArgs(args): log.warning("Message %d and args %s have invalid types. Message not sent.", msg, args) return if self.client: log.debug("Sending %s %s", msg, args) elif self.player and self.player.name: log.debug("Sending %s %s to %s", msg, args, self.player) else: log.debug("Sending %s %s to %s", msg, args, self.peerAddress().toString()) data = QByteArray() stream = QDataStream(data, self.WriteOnly) stream.writeInt32(int(msg)) for arg in args: if type(arg) == str: stream.writeInt32(len(arg)) stream.writeRawData(arg) elif type(arg) == int: stream.writeInt32(arg) elif type(arg) == long: stream.writeInt64(arg) self.write(data) self.messageSent.emit(msg, args)
class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) format = QAudioFormat() format.setChannels(1) format.setFrequency(22050) format.setSampleSize(16) format.setCodec("audio/pcm") format.setByteOrder(QAudioFormat.LittleEndian) format.setSampleType(QAudioFormat.SignedInt) self.output = QAudioOutput(format, self) self.frequency = 440 self.volume = 0 self.buffer = QBuffer() self.data = QByteArray() self.deviceLineEdit = QLineEdit() self.deviceLineEdit.setReadOnly(True) self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName()) self.pitchSlider = QSlider(Qt.Horizontal) self.pitchSlider.setMaximum(100) self.volumeSlider = QSlider(Qt.Horizontal) self.volumeSlider.setMaximum(32767) self.volumeSlider.setPageStep(1024) self.playButton = QPushButton(self.tr("&Play")) self.pitchSlider.valueChanged.connect(self.changeFrequency) self.volumeSlider.valueChanged.connect(self.changeVolume) self.playButton.clicked.connect(self.play) formLayout = QFormLayout() formLayout.addRow(self.tr("Device:"), self.deviceLineEdit) formLayout.addRow(self.tr("P&itch:"), self.pitchSlider) formLayout.addRow(self.tr("&Volume:"), self.volumeSlider) buttonLayout = QVBoxLayout() buttonLayout.addWidget(self.playButton) buttonLayout.addStretch() horizontalLayout = QHBoxLayout(self) horizontalLayout.addLayout(formLayout) horizontalLayout.addLayout(buttonLayout) def changeFrequency(self, value): self.frequency = 440 + (value * 2) def play(self): if self.output.state() == QAudio.ActiveState: self.output.stop() if self.buffer.isOpen(): self.buffer.close() self.createData() self.buffer.setData(self.data) self.buffer.open(QIODevice.ReadOnly) self.buffer.seek(0) self.output.start(self.buffer) def changeVolume(self, value): self.volume = value def createData(self): # Create 2 seconds of data with 22050 samples per second, each sample # being 16 bits (2 bytes). self.data.clear() for i in xrange(2 * 22050): t = i / 22050.0 value = int(self.volume * sin(2 * pi * self.frequency * t)) self.data.append(struct.pack("<h", value))
def OCRperformOCRPlayerBalance(x,y,w,h,flag = False): rvalue = '' img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h) #img= Image.open('/home/liutauras/Documents/Python/P0.912100785738.png') if(flag): img.save('P'+str(random.random())+'.png', 'png') buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) im = Image.open(strio) #im = Image.open('/home/liutauras/Documents/Python/PtestAllIn.png') pixdata = im.load(); for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 550: pixdata[x, y] = (255, 255, 255) else: pixdata[x, y] = (0, 0, 0) #Add extra space on each side for y in xrange(im.size[1]): pixdata[0,y] = (255, 255, 255) pixdata[1,y] = (255, 255, 255) pixdata[im.size[0]-1,y] = (255, 255, 255) pixdata[im.size[0]-2,y] = (255, 255, 255) for x in xrange(im.size[0]): pixdata[x,0] = (255, 255, 255) pixdata[x,1] = (255, 255, 255) pixdata[x,im.size[1]-1] = (255, 255, 255) pixdata[x,im.size[1]-2] = (255, 255, 255) nx, ny = im.size im = im.resize((nx*5, ny*5), Image.ANTIALIAS) enh = ImageEnhance.Contrast(im) pixdata = im.load() for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR) #rvalue = OCR_to_string(im,True) pixdata = im.load() #Spit by Character totalSumLast = 0 startX = 0 for x in xrange(im.size[0]): #Start of digits flag totalSum = 0 for y in xrange(im.size[1]): totalSum = totalSum + pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if(totalSum < totalSumLast and totalSumLast == 61200): startX = x for y in xrange(im.size[1]): pixdata[x, y] = (0, 0, 0) elif(totalSum > totalSumLast and totalSum == 61200 and startX != 0): #Detect start on y axis flagAllIn = 0 flagSittingOut = 0 startY = 0 for y1 in xrange(im.size[1]): if(flagAllIn == 1 or flagSittingOut == 1): break innerSum = 0 divTot = 0 for x1 in xrange(startX,x): innerSum = innerSum + sum(pixdata[x1, y1]) divTot = divTot + 1 innerSum = innerSum/divTot if(startY == 0 and innerSum < 630): startY = y1 elif(startY != 0 and innerSum > 630): for x1 in xrange(startX,x): pixdata[x1, startY] = (0, 200, 0) pixdata[x1, y1] = (0, 0, 200) #Total area sum totalAreaSum = 0 for x1 in xrange(startX,x): for y2 in xrange(startY,y1): totalAreaSum = totalAreaSum + sum(pixdata[x1, y2]) #Decoding digit if(totalAreaSum == 353945): flagAllIn = 1 rvalue = '0' break elif(totalAreaSum == 105910): rvalue = '-1' flagSittingOut = 1 elif(totalAreaSum == 8285): rvalue = rvalue + ',' elif(totalAreaSum == 230545): rvalue = rvalue + '0' elif(totalAreaSum == 199475): rvalue = rvalue + '1' elif(totalAreaSum == 346825): rvalue = rvalue + '2' elif(totalAreaSum == 362125): rvalue = rvalue + '3' elif(totalAreaSum == 379720): rvalue = rvalue + '4' elif(totalAreaSum == 304750): rvalue = rvalue + '5' elif(totalAreaSum == 295570): rvalue = rvalue + '6' elif(totalAreaSum == 453160): rvalue = rvalue + '7' elif(totalAreaSum == 219070): rvalue = rvalue + '8' elif(totalAreaSum == 310870): rvalue = rvalue + '9' startY = 0 startX = 0 for y in xrange(im.size[1]): pixdata[x, y] = (200, 0, 0) totalSumLast = totalSum rvalue = rvalue.replace('\n','').replace(' ','') if(flag): im.save("Pa"+str(random.random())+".png") rvalue = rvalue.replace(',','').replace(' ','').replace('.','') if(len(rvalue) > 0): return int(rvalue) else: return -2
def do_GET(self): print "get" global plotValues try: self.path = re.sub('[^.a-zA-Z0-9]', "", str(self.path)) if self.path == "" or self.path == None or self.path[:1] == ".": return if self.path.endswith(".html"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() return if self.path.endswith(".mjpeg"): self.thread = WorkThread() #self.thread.osc_received.connect(self.change) #self.connect(self.thread, thread.osc_received, self.change) self.thread.osc_received.connect(self.receive_osc) self.thread.start() self.send_response(200) self.plt = plt = PlotWindow(title="EKG", name="Merle") plt.addLegend() #plt = pg.plot(pen=(0, 3*1.3)) plt.resize(1280, 720) self.plotItem1 = plotItem1 = pg.PlotCurveItem(pen=pg.mkPen( 'r', width=4), name="bjoern") self.plotItem2 = plotItem2 = pg.PlotCurveItem(pen=pg.mkPen( 'g', width=4), name="merle") self.plotItem3 = plotItem3 = pg.PlotCurveItem(pen=pg.mkPen( 'b', width=4), name="uwe") plotItem1.setPos(0, 0 * 6) plotItem2.setPos(0, 1 * 6) plotItem3.setPos(0, 2 * 6) plt.addItem(plotItem1) plt.addItem(plotItem2) plt.addItem(plotItem3) plt.setLabel('left', "EKG") plt.setLabel('bottom', "Time") plt.showGrid(True, True) ba = plt.getAxis("bottom") bl = plt.getAxis("left") ba.setTicks([]) bl.setTicks([]) plt.setYRange(0, 254) #print type(plt) self.wfile.write( "Content-Type: multipart/x-mixed-replace; boundary=--aaboundary" ) self.wfile.write("\r\n\r\n") last = time.time() now = last while 1: plotItem1.setData(y=np.array(self.plot_data1), clear=True) plotItem2.setData(y=np.array(self.plot_data2), clear=True) plotItem3.setData(y=np.array(self.plot_data3), clear=True) #item = plt.plot(plot_data1, pen=(0, 3*1.3), clear=True) exporter = pg.exporters.ImageExporter.ImageExporter( plt.plotItem) exporter.parameters()['width'] = 1280 #exporter.parameters()['height'] = 720 name = 'tmpfile' img = exporter.export(name, True) buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "JPG", 100) JpegData = buffer.data() self.wfile.write("--aaboundary\r\n") self.wfile.write("Content-Type: image/jpeg\r\n") self.wfile.write("Content-length: %d\r\n\r\n" % len(JpegData)) self.wfile.write(JpegData) self.wfile.write("\r\n\r\n\r\n") now = time.time() dur = now - last #print dur wait = 0.04 - dur if wait > 0: time.sleep(wait) last = now return if self.path.endswith(".jpeg"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'image/jpeg') self.end_headers() self.wfile.write(f.read()) f.close() return return except IOError: self.send_error(404, 'File Not Found: %s' % self.path)
def send(self, method, url, headers, body, context=None): qurl = QUrl.fromEncoded(url) request = QNetworkRequest() request.setUrl(qurl) method = self.translate_method(method, request) host, useragent, content_type = None, None, None for name, value in headers.items(): lname = name.lower() if 'user-agent' == lname: useragent = value elif 'host' == lname: host = value elif 'content-type' == lname: content_type = value elif 'content-length' == lname: continue request.setRawHeader(name, value) if not host: request.setRawHeader('Host', str(qurl.host())) if not useragent: request.setRawHeader('User-Agent', self.framework.useragent()) if 'POST' == method and not content_type: request.setRawHeader('Content-Type', 'application/x-www-form-urlencoded') if not body: if method in ( 'POST', 'PUT', 'CUSTOM' ): # TODO: determine specific methods that expect content? body = '' else: device = None if method in ('GET', 'HEAD', 'DELETE'): # can't have body, because not supported by Qt network logic body = None device = None if body is not None: request.setRawHeader('Content-Length', str(len(body))) data = QByteArray(body) device = QBuffer(self) device.setData(data) device.open(QIODevice.ReadOnly) request.setAttribute(request.CacheLoadControlAttribute, request.AlwaysNetwork) if 'GET' == method: reply = self.networkAccessManager.get(request) elif 'HEAD' == method: reply = self.networkAccessManager.head(request) elif 'DELETE' == method: reply = self.networkAccessManager.head(request) elif 'POST' == method: reply = self.networkAccessManager.post(request, device) elif 'PUT' == method: reply = self.networkAccessManager.put(request, device) else: reply = self.networkAccessManager.sendCustomRequest( request, method, device) response = NetworkResponse(self.framework, self.callback, reply, context, self) return NetworkRequest(request, reply, response, context, self)