本文整理汇总了Python中PyQt5.QtCore.QBuffer类的典型用法代码示例。如果您正苦于以下问题:Python QBuffer类的具体用法?Python QBuffer怎么用?Python QBuffer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QBuffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write
def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
archive = VirtualFile()
archive.openStream(stream, "application/x-ufp", OpenMode.WriteOnly)
#Store the g-code from the scene.
archive.addContentType(extension = "gcode", mime_type = "text/x-gcode")
gcode_textio = StringIO() #We have to convert the g-code into bytes.
PluginRegistry.getInstance().getPluginObject("GCodeWriter").write(gcode_textio, None)
gcode = archive.getStream("/3D/model.gcode")
gcode.write(gcode_textio.getvalue().encode("UTF-8"))
archive.addRelation(virtual_path = "/3D/model.gcode", relation_type = "http://schemas.ultimaker.org/package/2018/relationships/gcode")
#Store the thumbnail.
if self._snapshot:
archive.addContentType(extension = "png", mime_type = "image/png")
thumbnail = archive.getStream("/Metadata/thumbnail.png")
thumbnail_buffer = QBuffer()
thumbnail_buffer.open(QBuffer.ReadWrite)
thumbnail_image = self._snapshot
thumbnail_image.save(thumbnail_buffer, "PNG")
thumbnail.write(thumbnail_buffer.data())
archive.addRelation(virtual_path = "/Metadata/thumbnail.png", relation_type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail", origin = "/3D/model.gcode")
else:
Logger.log("d", "Thumbnail not created, cannot save it")
archive.close()
return True
示例2: _addIcon
def _addIcon(self):
filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif);;"
"All files (*.*)")
fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
self.tr("Open File"), self.latestDir,
filter_)
if fileName:
file_info = QFileInfo(fileName)
self.latestDir = file_info.absolutePath()
image = QImage()
if image.load(fileName):
maxWidth = 22
maxHeight = 15
if image.width() > maxWidth or image.height() > maxHeight:
scaledImage = image.scaled(maxWidth, maxHeight,
Qt.KeepAspectRatio, Qt.SmoothTransformation)
else:
scaledImage = image
ba = QByteArray()
buffer = QBuffer(ba)
buffer.open(QIODevice.WriteOnly)
scaledImage.save(buffer, 'png')
model = self.model()
index = model.index(self.selectedIndex().row(), model.fieldIndex('icon'))
model.setData(index, ba)
示例3: dropEvent
def dropEvent(self, event):
mimeData = event.mimeData()
if mimeData.hasUrls():
paths = mimeData.urls()
# pick just one image
path = paths[0].toLocalFile()
fileName = os.path.basename(path)
with open(path, "rb") as imgFile:
data = imgFile.read()
ext = os.path.splitext(path)[1][1:]
# TODO: make sure we cleanup properly when replacing an image with
# another
if ext.lower() != "png":
# convert
img = QImage(path)
data = QByteArray()
buffer = QBuffer(data)
buffer.open(QIODevice.WriteOnly)
img.save(buffer, 'PNG')
# format
data = bytearray(data)
fileName = "%s.png" % os.path.splitext(fileName)[0]
imageSet = self._glyph.font.images
try:
imageSet[fileName] = data
except Exception as e:
errorReports.showCriticalException(e)
return
image = self._glyph.instantiateImage()
image.fileName = fileName
event.setAccepted(True)
else:
super().dropEvent(event)
示例4: store_file
def store_file(self, id, file):
id = id.replace('/', '_')
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
icon.content_type = 'image/png'
else:
unlink(filename)
icon = None
self.iconmap[id] = icon
return icon
示例5: mouseMoveEvent
def mouseMoveEvent(self, event):
""" If the mouse moves far enough when the left mouse button is held
down, start a drag and drop operation.
"""
if not event.buttons() & Qt.LeftButton:
return
if (event.pos() - self.dragStartPosition).manhattanLength() \
< QApplication.startDragDistance():
return
if not self.hasImage:
return
drag = QDrag(self)
mimeData = QMimeData()
output = QByteArray()
outputBuffer = QBuffer(output)
outputBuffer.open(QIODevice.WriteOnly)
self.imageLabel.pixmap().toImage().save(outputBuffer, 'PNG')
outputBuffer.close()
mimeData.setData('image/png', output)
drag.setMimeData(mimeData)
drag.setPixmap(self.imageLabel.pixmap().scaled(64, 64, Qt.KeepAspectRatio))
drag.setHotSpot(QPoint(drag.pixmap().width() / 2,
drag.pixmap().height()))
drag.start()
示例6: mimeData
def mimeData(self, indexes):
"""
Public method to return the mime data.
@param indexes list of indexes (QModelIndexList)
@return mime data (QMimeData)
"""
from .XbelWriter import XbelWriter
data = QByteArray()
stream = QDataStream(data, QIODevice.WriteOnly)
urls = []
for index in indexes:
if index.column() != 0 or not index.isValid():
continue
encodedData = QByteArray()
buffer = QBuffer(encodedData)
buffer.open(QIODevice.ReadWrite)
writer = XbelWriter()
parentNode = self.node(index)
writer.write(buffer, parentNode)
stream << encodedData
urls.append(index.data(self.UrlRole))
mdata = QMimeData()
mdata.setData(self.MIMETYPE, data)
mdata.setUrls(urls)
return mdata
示例7: store_data
def store_data(self, id, data):
id = id.replace('/', '_')
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
icon.content_type = 'image/png'
else:
unlink(filename)
icon = None
self.iconmap[id] = icon
return icon
示例8: loadFromMemory
def loadFromMemory(self):
""" This slot function is called in the second Dialog process, when the
user presses the "Load Image from Shared Memory" button. First, it
attaches the process to the shared memory segment created by the first
Dialog process. Then it locks the segment for exclusive access, copies
the image data from the segment into a QBuffer, and streams the QBuffer
into a QImage. Then it unlocks the shared memory segment, detaches
from it, and finally displays the QImage in the Dialog.
"""
if not self.sharedMemory.attach():
self.ui.label.setText(
"Unable to attach to shared memory segment.\nLoad an "
"image first.")
return
buf = QBuffer()
ins = QDataStream(buf)
image = QImage()
self.sharedMemory.lock()
buf.setData(self.sharedMemory.constData())
buf.open(QBuffer.ReadOnly)
ins >> image
self.sharedMemory.unlock()
self.sharedMemory.detach()
self.ui.label.setPixmap(QPixmap.fromImage(image))
示例9: dropMimeData
def dropMimeData(self, data, action, row, column, parent):
"""
Public method to accept the mime data of a drop action.
@param data reference to the mime data (QMimeData)
@param action drop action requested (Qt.DropAction)
@param row row number (integer)
@param column column number (integer)
@param parent index of the parent node (QModelIndex)
@return flag indicating successful acceptance of the data (boolean)
"""
if action == Qt.IgnoreAction:
return True
if column > 0:
return False
parentNode = self.node(parent)
if not data.hasFormat(self.MIMETYPE):
if not data.hasUrls():
return False
from .BookmarkNode import BookmarkNode
node = BookmarkNode(BookmarkNode.Bookmark, parentNode)
node.url = bytes(data.urls()[0].toEncoded()).decode()
if data.hasText():
node.title = data.text()
else:
node.title = node.url
self.__bookmarksManager.addBookmark(parentNode, node, row)
return True
ba = data.data(self.MIMETYPE)
stream = QDataStream(ba, QIODevice.ReadOnly)
if stream.atEnd():
return False
undoStack = self.__bookmarksManager.undoRedoStack()
undoStack.beginMacro("Move Bookmarks")
from .XbelReader import XbelReader
while not stream.atEnd():
encodedData = QByteArray()
stream >> encodedData
buffer = QBuffer(encodedData)
buffer.open(QIODevice.ReadOnly)
reader = XbelReader()
rootNode = reader.read(buffer)
for bookmarkNode in rootNode.children():
rootNode.remove(bookmarkNode)
row = max(0, row)
self.__bookmarksManager.addBookmark(
parentNode, bookmarkNode, row)
self.__endMacro = True
return True
示例10: image_and_format_from_data
def image_and_format_from_data(data):
' Create an image object from the specified data which should be a bytestring and also return the format of the image '
ba = QByteArray(data)
buf = QBuffer(ba)
buf.open(QBuffer.ReadOnly)
r = QImageReader(buf)
fmt = bytes(r.format()).decode('utf-8')
return r.read(), fmt
示例11: take_screenshot
def take_screenshot(self):
byte_array = QByteArray()
buffer = QBuffer(byte_array)
buffer.open(QIODevice.WriteOnly)
image = self.__screen.grabWindow(QApplication.desktop().winId())
image.save(buffer, "PNG")
return str(byte_array.toBase64())[1:]
示例12: requestStarted
def requestStarted(self, job):
"""Handle a request for a qute: scheme.
This method must be reimplemented by all custom URL scheme handlers.
The request is asynchronous and does not need to be handled right away.
Args:
job: QWebEngineUrlRequestJob
"""
url = job.requestUrl()
if url.scheme() in ['chrome-error', 'chrome-extension']:
# WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378
job.fail(QWebEngineUrlRequestJob.UrlInvalid)
return
if not self._check_initiator(job):
return
if job.requestMethod() != b'GET':
job.fail(QWebEngineUrlRequestJob.RequestDenied)
return
assert url.scheme() == 'qute'
log.misc.debug("Got request for {}".format(url.toDisplayString()))
try:
mimetype, data = qutescheme.data_for_url(url)
except qutescheme.Error as e:
errors = {
qutescheme.NotFoundError:
QWebEngineUrlRequestJob.UrlNotFound,
qutescheme.UrlInvalidError:
QWebEngineUrlRequestJob.UrlInvalid,
qutescheme.RequestDeniedError:
QWebEngineUrlRequestJob.RequestDenied,
qutescheme.SchemeOSError:
QWebEngineUrlRequestJob.UrlNotFound,
qutescheme.Error:
QWebEngineUrlRequestJob.RequestFailed,
}
exctype = type(e)
log.misc.error("{} while handling qute://* URL".format(
exctype.__name__))
job.fail(errors[exctype])
except qutescheme.Redirect as e:
qtutils.ensure_valid(e.url)
job.redirect(e.url)
else:
log.misc.debug("Returning {} data".format(mimetype))
# We can't just use the QBuffer constructor taking a QByteArray,
# because that somehow segfaults...
# https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html
buf = QBuffer(parent=self)
buf.open(QIODevice.WriteOnly)
buf.write(data)
buf.seek(0)
buf.close()
job.reply(mimetype.encode('ascii'), buf)
示例13: fillImageFaster
def fillImageFaster(self, begin, paint, current, image):
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
image.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
ImageDraw.floodfill(pil_im, begin, (paint.red(), paint.green(), paint.blue()))
self.image().image = QtGui.QImage(pil_im.convert("RGB").tobytes("raw", "RGB"), pil_im.size[0], pil_im.size[1], QtGui.QImage.Format_RGB888)
self.update()
示例14: sendMessage
def sendMessage(self):
textbuf = QBuffer()
textbuf.open(QBuffer.ReadWrite)
messageText = QDataStream(textbuf)
messageText << self.ui.messageBox.text
size = textbuf.size()
if not self.shareMemory.create(size):
return
size = min(self.shareMemory.size(), size)
self.sharedMemory.lock()
示例15: loadFromFile
def loadFromFile(self):
""" This slot function is called when the "Load Image From File..."
button is pressed on the firs Dialog process. First, it tests whether
the process is already connected to a shared memory segment and, if so,
detaches from that segment. This ensures that we always start the
example from the beginning if we run it multiple times with the same
two Dialog processes. After detaching from an existing shared memory
segment, the user is prompted to select an image file. The selected
file is loaded into a QImage. The QImage is displayed in the Dialog
and streamed into a QBuffer with a QDataStream. Next, it gets a new
shared memory segment from the system big enough to hold the image data
in the QBuffer, and it locks the segment to prevent the second Dialog
process from accessing it. Then it copies the image from the QBuffer
into the shared memory segment. Finally, it unlocks the shared memory
segment so the second Dialog process can access it. After self
function runs, the user is expected to press the "Load Image from
Shared Memory" button on the second Dialog process.
"""
if self.sharedMemory.isAttached():
self.detach()
self.ui.label.setText("Select an image file")
fileName, _ = QFileDialog.getOpenFileName(self, None, None,
"Images (*.png *.xpm *.jpg)")
image = QImage()
if not image.load(fileName):
self.ui.label.setText(
"Selected file is not an image, please select another.")
return
self.ui.label.setPixmap(QPixmap.fromImage(image))
# Load into shared memory.
buf = QBuffer()
buf.open(QBuffer.ReadWrite)
out = QDataStream(buf)
out << image
size = buf.size()
if not self.sharedMemory.create(size):
self.ui.label.setText("Unable to create shared memory segment.")
return
size = min(self.sharedMemory.size(), size)
self.sharedMemory.lock()
# Copy image data from buf into shared memory area.
self.sharedMemory.data()[:] = buf.data().data()
self.sharedMemory.unlock()