本文整理汇总了Python中PyQt4.QtCore.QBuffer.data方法的典型用法代码示例。如果您正苦于以下问题:Python QBuffer.data方法的具体用法?Python QBuffer.data怎么用?Python QBuffer.data使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtCore.QBuffer
的用法示例。
在下文中一共展示了QBuffer.data方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: screenshot
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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 }
示例2: _getPng
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
def _getPng(self, width=None, height=None):
image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
self.web_page.mainFrame().render(painter)
painter.end()
if width:
image = image.scaledToWidth(width, Qt.SmoothTransformation)
if height:
image = image.copy(0, 0, width, height)
b = QBuffer()
image.save(b, "png")
return bytes(b.data())
示例3: QIm2PIL
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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
示例4: _render
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
def _render(self):
self.setViewportSize(QSize(self.vwidth, self.vheight))
image = QImage(self.viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
self.mainFrame().render(painter)
painter.end()
if self.width:
image = image.scaledToWidth(self.width, Qt.SmoothTransformation)
if self.height:
image = image.copy(0, 0, self.width, self.height)
b = QBuffer()
image.save(b, "png")
return str(b.data())
示例5: OCRperformOCRName
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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
示例6: _getPng
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
def _getPng(self, width=None, height=None, b64=False):
self.log("getting PNG %s" % id(self.splash_request))
image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
self.web_page.mainFrame().render(painter)
painter.end()
self.web_page.har_log.store_timing("_onScreenshotPrepared")
if width:
image = image.scaledToWidth(width, Qt.SmoothTransformation)
if height:
image = image.copy(0, 0, width, height)
b = QBuffer()
image.save(b, "png")
result = bytes(b.data())
if b64:
result = base64.b64encode(result)
self.web_page.har_log.store_timing("_onPngRendered")
return result
示例7: store_file
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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
示例8: store_data
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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
示例9: to_png
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
def to_png(self, complevel=defaults.PNG_COMPRESSION_LEVEL):
quality = 90 - (complevel * 10)
buf = QBuffer()
self.img.save(buf, 'png', quality=quality)
return bytes(buf.data())
示例10: render
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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()
示例11: getLegendGraphic
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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()
示例12: Connection
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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:
#.........这里部分代码省略.........
示例13: renderer
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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()
示例14: to_jpeg
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
def to_jpeg(self, quality=None):
if quality is None:
quality = defaults.JPEG_QUALITY
buf = QBuffer()
self.img.save(buf, 'jpeg', quality)
return bytes(buf.data())
示例15: OCRperformOCRDigit
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import data [as 别名]
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
#.........这里部分代码省略.........