本文整理汇总了Python中PyQt5.Qt.QPainter类的典型用法代码示例。如果您正苦于以下问题:Python QPainter类的具体用法?Python QPainter怎么用?Python QPainter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QPainter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scale_image
def scale_image(data, width=60, height=80, compression_quality=70, as_png=False, preserve_aspect_ratio=True):
''' Scale an image, returning it as either JPEG or PNG data (bytestring).
Transparency is alpha blended with white when converting to JPEG. Is thread
safe and does not require a QApplication. '''
# We use Qt instead of ImageMagick here because ImageMagick seems to use
# some kind of memory pool, causing memory consumption to sky rocket.
if isinstance(data, QImage):
img = data
else:
img = QImage()
if not img.loadFromData(data):
raise ValueError('Could not load image for thumbnail generation')
if preserve_aspect_ratio:
scaled, nwidth, nheight = fit_image(img.width(), img.height(), width, height)
if scaled:
img = img.scaled(nwidth, nheight, Qt.KeepAspectRatio, Qt.SmoothTransformation)
else:
if img.width() != width or img.height() != height:
img = img.scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
if not as_png and img.hasAlphaChannel():
nimg = QImage(img.size(), QImage.Format_RGB32)
nimg.fill(Qt.white)
p = QPainter(nimg)
p.drawImage(0, 0, img)
p.end()
img = nimg
ba = QByteArray()
buf = QBuffer(ba)
buf.open(QBuffer.WriteOnly)
fmt = 'PNG' if as_png else 'JPEG'
if not img.save(buf, fmt, quality=compression_quality):
raise ValueError('Failed to export thumbnail image to: ' + fmt)
return img.width(), img.height(), ba.data()
示例2: render_html
def render_html(self, ok):
try:
if not ok:
return
cwidth, cheight = self.page.mainFrame().contentsSize().width(), self.page.mainFrame().contentsSize().height()
self.page.setViewportSize(QSize(cwidth, cheight))
factor = float(self.width)/cwidth if cwidth > self.width else 1
cutoff_height = int(self.height/factor)-3
image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
image.setDotsPerMeterX(self.dpi*(100/2.54))
image.setDotsPerMeterY(self.dpi*(100/2.54))
painter = QPainter(image)
self.page.mainFrame().render(painter)
painter.end()
cheight = image.height()
cwidth = image.width()
pos = 0
while pos < cheight:
img = image.copy(0, pos, cwidth, min(cheight-pos, cutoff_height))
pos += cutoff_height-20
if cwidth > self.width:
img = img.scaledToWidth(self.width, Qt.SmoothTransform)
f = os.path.join(self.tdir, '%d.png'%pos)
img.save(f)
self.images.append((f, img.width(), img.height()))
finally:
QApplication.quit()
示例3: __call__
def __call__(self, ok):
from PyQt5.Qt import QImage, QPainter, QByteArray, QBuffer
try:
if not ok:
raise RuntimeError('Rendering of HTML failed.')
de = self.page.mainFrame().documentElement()
pe = de.findFirst('parsererror')
if not pe.isNull():
raise ParserError(pe.toPlainText())
image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
image.setDotsPerMeterX(96*(100/2.54))
image.setDotsPerMeterY(96*(100/2.54))
painter = QPainter(image)
self.page.mainFrame().render(painter)
painter.end()
ba = QByteArray()
buf = QBuffer(ba)
buf.open(QBuffer.WriteOnly)
image.save(buf, 'JPEG')
self.data = str(ba.data())
except Exception as e:
self.exception = e
self.traceback = traceback.format_exc()
finally:
self.loop.exit(0)
示例4: paintEvent
def paintEvent(self, ev):
p = QPainter(self)
c = color('tab tree background', None)
if c:
p.fillRect(ev.rect(), QColor(c))
p.end()
QWidget.paintEvent(self, ev)
示例5: paintEvent
def paintEvent(self, ev):
if self._animated_size < 1.0:
rect = self.rect()
painter = QPainter(self)
pal = self.palette()
col = pal.color(pal.Button)
rect.setLeft(rect.left() + (rect.width() * self._animated_size))
painter.setClipRect(rect)
painter.fillRect(self.rect(), col)
示例6: add_image
def add_image(self, img, cache_key):
ref = self.get_image(cache_key)
if ref is not None:
return ref
fmt = img.format()
image = QImage(img)
if (image.depth() == 1 and img.colorTable().size() == 2 and
img.colorTable().at(0) == QColor(Qt.black).rgba() and
img.colorTable().at(1) == QColor(Qt.white).rgba()):
if fmt == QImage.Format_MonoLSB:
image = image.convertToFormat(QImage.Format_Mono)
fmt = QImage.Format_Mono
else:
if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
image = image.convertToFormat(QImage.Format_ARGB32)
fmt = QImage.Format_ARGB32
w = image.width()
h = image.height()
d = image.depth()
if fmt == QImage.Format_Mono:
bytes_per_line = (w + 7) >> 3
data = image.constBits().asstring(bytes_per_line * h)
return self.write_image(data, w, h, d, cache_key=cache_key)
has_alpha = False
soft_mask = None
if fmt == QImage.Format_ARGB32:
tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
sdata = bytearray(tmask)
vals = set(sdata)
vals.discard(255) # discard opaque pixels
has_alpha = bool(vals)
if has_alpha:
# Blend image onto a white background as otherwise Qt will render
# transparent pixels as black
background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
background.fill(Qt.white)
painter = QPainter(background)
painter.drawImage(0, 0, image)
painter.end()
image = background
ba = QByteArray()
buf = QBuffer(ba)
image.save(buf, 'jpeg', 94)
data = bytes(ba.data())
if has_alpha:
soft_mask = self.write_image(tmask, w, h, 8)
return self.write_image(data, w, h, 32, dct=True,
soft_mask=soft_mask, cache_key=cache_key)
示例7: paintEvent
def paintEvent(self, ev):
if self.mouse_over:
p = QPainter(self)
tool = QStyleOption()
tool.rect = self.rect()
tool.state = QStyle.State_Raised | QStyle.State_Active | QStyle.State_MouseOver
s = self.style()
s.drawPrimitive(QStyle.PE_PanelButtonTool, tool, p, self)
p.end()
return QLabel.paintEvent(self, ev)
示例8: setup_printer
def setup_printer(self, outpath):
self.printer = self.painter = None
printer = get_pdf_printer(self.opts, output_file_name=outpath)
painter = QPainter(printer)
zoomx = printer.logicalDpiX()/self.view.logicalDpiX()
zoomy = printer.logicalDpiY()/self.view.logicalDpiY()
painter.scale(zoomx, zoomy)
pr = printer.pageRect()
self.printer, self.painter = printer, painter
self.viewport_size = QSize(pr.width()/zoomx, pr.height()/zoomy)
self.page.setViewportSize(self.viewport_size)
示例9: screenshot
def screenshot(self, file_name):
# while self.load_status == "started":
# time.sleep(0.15)
self.page().setViewportSize(self.page().mainFrame().contentsSize())
image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
self.page().mainFrame().render(painter)
painter.end()
image.save(file_name)
示例10: run
def run(dev, func):
p = QPainter(dev)
if isinstance(dev, PdfDevice):
dev.init_page()
xmax, ymax = p.viewport().width(), p.viewport().height()
try:
func(p, xmax, ymax)
finally:
p.end()
if isinstance(dev, PdfDevice):
if dev.engine.errors_occurred:
raise SystemExit(1)
示例11: paintEvent
def paintEvent(self, ev):
p = QPainter(self)
p.setClipRect(ev.rect())
bg = self.palette().color(QPalette.AlternateBase)
if self.hovering:
bg = bg.lighter(115)
p.fillRect(self.rect(), bg)
try:
p.drawText(self.rect(), Qt.AlignLeft|Qt.AlignVCenter|Qt.TextSingleLine, self.rendered_text)
finally:
p.end()
示例12: image_to_data
def image_to_data(img, compression_quality=95, fmt='JPEG'):
ba = QByteArray()
buf = QBuffer(ba)
buf.open(QBuffer.WriteOnly)
fmt = fmt.upper()
if img.hasAlphaChannel() and fmt in 'JPEG JPG'.split():
nimg = QImage(img.size(), QImage.Format_RGB32)
nimg.fill(Qt.white)
p = QPainter(nimg)
p.drawImage(0, 0, img)
p.end()
img = nimg
if not img.save(buf, fmt, quality=compression_quality):
raise ValueError('Failed to export image as ' + fmt)
return ba.data()
示例13: render_svg
def render_svg(widget, path):
img = QPixmap()
rend = QSvgRenderer()
if rend.load(path):
dpr = getattr(widget, 'devicePixelRatioF', widget.devicePixelRatio)()
sz = rend.defaultSize()
h = (max_available_height() - 50)
w = int(h * sz.height() / float(sz.width()))
pd = QImage(w * dpr, h * dpr, QImage.Format_RGB32)
pd.fill(Qt.white)
p = QPainter(pd)
rend.render(p)
p.end()
img = QPixmap.fromImage(pd)
img.setDevicePixelRatio(dpr)
return img
示例14: dump
def dump(self, items, out_stream, pdf_metadata):
opts = self.opts
page_size = get_page_size(self.opts)
ml, mr = opts.margin_left, opts.margin_right
self.doc = PdfDevice(
out_stream, page_size=page_size, left_margin=ml,
top_margin=opts.margin_top, right_margin=mr,
bottom_margin=opts.margin_bottom,
errors=self.log.error, debug=self.log.debug, compress=not
opts.uncompressed_pdf, opts=opts, mark_links=opts.pdf_mark_links)
self.painter = QPainter(self.doc)
self.doc.set_metadata(title=pdf_metadata.title,
author=pdf_metadata.author,
tags=pdf_metadata.tags, mi=pdf_metadata.mi)
self.doc_title = pdf_metadata.title
self.doc_author = pdf_metadata.author
for imgpath in items:
self.log.debug('Processing %s...' % imgpath)
self.doc.init_page()
p = QPixmap()
with lopen(imgpath, 'rb') as f:
if not p.loadFromData(f.read()):
raise ValueError('Could not read image from: {}'.format(imgpath))
draw_image_page(QRect(*self.doc.full_page_rect),
self.painter, p,
preserve_aspect_ratio=True)
self.doc.end_page()
if self.toc is not None and len(self.toc) > 0:
self.doc.add_outline(self.toc)
self.painter.end()
if self.doc.errors_occurred:
raise Exception('PDF Output failed, see log for details')
示例15: overlay_image
def overlay_image(img, canvas=None, left=0, top=0):
if canvas is None:
canvas = QImage(img.size(), QImage.Format_RGB32)
canvas.fill(Qt.white)
if imageops is None:
# This is for people running from source who have not updated the
# binary and so do not have the imageops module
from PyQt5.Qt import QPainter
from calibre.gui2 import ensure_app
ensure_app()
p = QPainter(canvas)
p.drawImage(left, top, img)
p.end()
else:
imageops.overlay(img, canvas, left, top)
return canvas