def render_cover(self, book_id): if self.ignore_render_requests.is_set(): return tcdata, timestamp = self.thumbnail_cache[book_id] use_cache = False if timestamp is None: # Not in cache has_cover, cdata, timestamp = self.model( ).db.new_api.cover_or_cache(book_id, 0) else: has_cover, cdata, timestamp = self.model( ).db.new_api.cover_or_cache(book_id, timestamp) if has_cover and cdata is None: # The cached cover is fresh cdata = tcdata use_cache = True if has_cover: p = QImage() p.loadFromData(cdata, CACHE_FORMAT if cdata is tcdata else 'JPEG') dpr = self.device_pixel_ratio p.setDevicePixelRatio(dpr) if p.isNull() and cdata is tcdata: # Invalid image in cache self.thumbnail_cache.invalidate((book_id, )) self.update_item.emit(book_id) return cdata = None if p.isNull() else p if not use_cache: # cache is stale if cdata is not None: width, height = p.width(), p.height() scaled, nwidth, nheight = fit_image( width, height, int(dpr * self.delegate.cover_size.width()), int(dpr * self.delegate.cover_size.height())) if scaled: if self.ignore_render_requests.is_set(): return p = p.scaled(nwidth, nheight, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p.setDevicePixelRatio(dpr) cdata = p # update cache if cdata is None: self.thumbnail_cache.invalidate((book_id, )) else: try: self.thumbnail_cache.insert(book_id, timestamp, image_to_data(cdata)) except EncodeError as err: self.thumbnail_cache.invalidate((book_id, )) prints(err) except Exception: import traceback traceback.print_exc() elif tcdata is not None: # Cover was removed, but it exists in cache, remove from cache self.thumbnail_cache.invalidate((book_id, )) self.delegate.cover_cache.set(book_id, cdata) self.update_item.emit(book_id)
def __init__(self, parent=None): QStackedWidget.__init__(self, parent) self.welcome = w = QLabel('<p>'+_( 'Double click a file in the left panel to start editing' ' it.')) self.addWidget(w) w.setWordWrap(True) w.setAlignment(Qt.AlignTop | Qt.AlignHCenter) self.container = c = QWidget(self) self.addWidget(c) l = c.l = QVBoxLayout(c) c.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.editor_tabs = t = QTabWidget(c) l.addWidget(t) t.setDocumentMode(True) t.setTabsClosable(True) t.setMovable(True) pal = self.palette() if pal.color(pal.WindowText).lightness() > 128: i = QImage(I('modified.png')) i.invertPixels() self.modified_icon = QIcon(QPixmap.fromImage(i)) else: self.modified_icon = QIcon(I('modified.png')) self.editor_tabs.currentChanged.connect(self.current_editor_changed) self.editor_tabs.tabCloseRequested.connect(self._close_requested) self.search_panel = SearchPanel(self) l.addWidget(self.search_panel) self.restore_state() self.editor_tabs.tabBar().installEventFilter(self)
def get_icon(path, pixmap_to_data=None, as_data=False, size=64): if not path: return with TemporaryDirectory() as tdir: iconset = os.path.join(tdir, 'output.iconset') try: subprocess.check_call( ['iconutil', '-c', 'iconset', '-o', 'output.iconset', path], cwd=tdir) except subprocess.CalledProcessError: return try: names = os.listdir(iconset) except EnvironmentError: return if not names: return from PyQt5.Qt import QImage, Qt names.sort(key=numeric_sort_key) for name in names: m = re.search(r'(\d+)x\d+', name) if m is not None and int(m.group(1)) >= size: ans = QImage(os.path.join(iconset, name)) if not ans.isNull(): break else: return ans = ans.scaled(size, size, transformMode=Qt.SmoothTransformation) if as_data: ans = pixmap_to_data(ans) return ans
def drag_icon(self, cover, multiple): cover = cover.scaledToHeight(120, Qt.SmoothTransformation) if multiple: base_width = cover.width() base_height = cover.height() base = QImage(base_width + 21, base_height + 21, QImage.Format_ARGB32_Premultiplied) base.fill(QColor(255, 255, 255, 0).rgba()) p = QPainter(base) rect = QRect(20, 0, base_width, base_height) p.fillRect(rect, QColor('white')) p.drawRect(rect) rect.moveLeft(10) rect.moveTop(10) p.fillRect(rect, QColor('white')) p.drawRect(rect) rect.moveLeft(0) rect.moveTop(20) p.fillRect(rect, QColor('white')) p.save() p.setCompositionMode(p.CompositionMode_SourceAtop) p.drawImage(rect.topLeft(), cover) p.restore() p.drawRect(rect) p.end() cover = base return QPixmap.fromImage(cover)
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)
def generate_cover(mi, prefs=None, as_qimage=False): init_environment() prefs = prefs or cprefs prefs = {k: prefs.get(k) for k in cprefs.defaults} prefs = Prefs(**prefs) color_theme = random.choice(load_color_themes(prefs)) style = random.choice(load_styles(prefs))(color_theme, prefs) title, subtitle, footer = format_text(mi, prefs) img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format_ARGB32) title_block, subtitle_block, footer_block = layout_text( prefs, img, title, subtitle, footer, img.height() // 3, style) p = QPainter(img) rect = QRect(0, 0, img.width(), img.height()) colors = style(p, rect, color_theme, title_block, subtitle_block, footer_block) for block, color in zip((title_block, subtitle_block, footer_block), colors): p.setPen(color) block.draw(p) p.end() img.setText('Generated cover', '%s %s' % (__appname__, __version__)) if as_qimage: return img return pixmap_to_data(img)
def get_pix_map(self, map_type=None, map_pos=None, scale=None, tags=None): """Получение изображения карты.""" # Если в метод не переданы какие-либо параметры, используем текущие # параметры карты if map_type is None: map_type = self.map_type if map_pos is None: map_pos = self.map_pos if scale is None: scale = self.scale if tags is None: tags = self.tags map_params = { "l": map_type, 'll': ','.join(map(str, map_pos)), 'z': str(scale), 'pt': '~'.join(map(str, tags)) } key = tuple(map_params.values()) pix_map = self.pix_maps.get(key) if pix_map is None: response = perform_request(MAP_API_SERVER, params=map_params) image = QImage().fromData(response.content) pix_map = QPixmap().fromImage(image) self.pix_maps[key] = pix_map return pix_map
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()
def __init__(self, stream, page_size, compress=False, mark_links=False, debug=print): self.stream = HashingStream(stream) self.compress = compress self.write_line(PDFVER) self.write_line(u'%íì¦"'.encode('utf-8')) creator = ('%s %s [https://calibre-ebook.com]' % (__appname__, __version__)) self.write_line('%% Created by %s' % creator) self.objects = IndirectObjects() self.objects.add(PageTree(page_size)) self.objects.add(Catalog(self.page_tree)) self.current_page = Page(self.page_tree, compress=self.compress) self.info = Dictionary({ 'Creator': String(creator), 'Producer': String(creator), 'CreationDate': utcnow(), }) self.stroke_opacities, self.fill_opacities = {}, {} self.font_manager = FontManager(self.objects, self.compress) self.image_cache = {} self.pattern_cache, self.shader_cache = {}, {} self.debug = debug self.page_size = page_size self.links = Links(self, mark_links, page_size) i = QImage(1, 1, QImage.Format_ARGB32) i.fill(qRgba(0, 0, 0, 255)) self.alpha_bit = i.constBits().asstring(4).find(b'\xff')
def create_icon(text, palette=None, sz=None, divider=2, fill='white'): if isinstance(fill, basestring): fill = QColor(fill) sz = sz or int( math.ceil(tprefs['toolbar_icon_size'] * QApplication.instance().devicePixelRatio())) if palette is None: palette = QApplication.palette() img = QImage(sz, sz, QImage.Format_ARGB32) img.fill(Qt.transparent) p = QPainter(img) p.setRenderHints(p.TextAntialiasing | p.Antialiasing) if fill is not None: qDrawShadeRect(p, img.rect(), palette, fill=fill, lineWidth=1, midLineWidth=1) f = p.font() f.setFamily('Liberation Sans'), f.setPixelSize(int( sz // divider)), f.setBold(True) p.setFont(f), p.setPen(Qt.black) p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text) p.end() return QIcon(QPixmap.fromImage(img))
def generate_masthead(title, output_path=None, width=600, height=60, as_qimage=False, font_family=None): init_environment() font_family = font_family or cprefs[ 'title_font_family'] or 'Liberation Serif' img = QImage(width, height, QImage.Format_ARGB32) img.fill(Qt.white) p = QPainter(img) p.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) f = QFont(font_family) f.setStyleStrategy(QFont.PreferAntialias) f.setPixelSize((height * 3) // 4), f.setBold(True) p.setFont(f) p.drawText(img.rect(), Qt.AlignLeft | Qt.AlignVCenter, sanitize(title)) p.end() if as_qimage: return img data = pixmap_to_data(img) if output_path is None: return data with open(output_path, 'wb') as f: f.write(data)
def image_from_data(data): ' Create an image object from data, which should be a bytestring. ' if isinstance(data, QImage): return data i = QImage() if not i.loadFromData(data): raise NotImage('Not a valid image') return i
def add_borders_to_image(img, left=0, top=0, right=0, bottom=0, border_color='#ffffff'): img = image_from_data(img) if not (left > 0 or right > 0 or top > 0 or bottom > 0): return img canvas = QImage(img.width() + left + right, img.height() + top + bottom, QImage.Format_RGB32) canvas.fill(QColor(border_color)) overlay_image(img, canvas, left, top) return canvas
def overlay_image(img, canvas=None, left=0, top=0): ' Overlay the `img` onto the canvas at the specified position ' if canvas is None: canvas = QImage(img.size(), QImage.Format_RGB32) canvas.fill(Qt.white) left, top = int(left), int(top) imageops.overlay(img, canvas, left, top) return canvas
def calibre_cover2(title, author_string='', series_string='', prefs=None, as_qimage=False, logo_path=None): init_environment() title, subtitle, footer = '<b>' + escape_formatting( title), '<i>' + escape_formatting( series_string), '<b>' + escape_formatting(author_string) prefs = prefs or cprefs prefs = {k: prefs.get(k) for k in cprefs.defaults} scale = 800. / prefs['cover_height'] scale_cover(prefs, scale) prefs = Prefs(**prefs) img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format.Format_ARGB32) img.fill(Qt.GlobalColor.white) # colors = to_theme('ffffff ffffff 000000 000000') color_theme = theme_to_colors(fallback_colors) class CalibeLogoStyle(Style): NAME = GUI_NAME = 'calibre' def __call__(self, painter, rect, color_theme, title_block, subtitle_block, footer_block): top = title_block.position.y + 10 extra_spacing = subtitle_block.line_spacing // 2 if subtitle_block.line_spacing else title_block.line_spacing // 3 height = title_block.height + subtitle_block.height + extra_spacing + title_block.leading top += height + 25 bottom = footer_block.position.y - 50 logo = QImage(logo_path or I('library.png')) pwidth, pheight = rect.width(), bottom - top scaled, width, height = fit_image(logo.width(), logo.height(), pwidth, pheight) x, y = (pwidth - width) // 2, (pheight - height) // 2 rect = QRect(x, top + y, width, height) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) painter.drawImage(rect, logo) return self.ccolor1, self.ccolor1, self.ccolor1 style = CalibeLogoStyle(color_theme, prefs) title_block, subtitle_block, footer_block = layout_text( prefs, img, title, subtitle, footer, img.height() // 3, style) p = QPainter(img) rect = QRect(0, 0, img.width(), img.height()) colors = style(p, rect, color_theme, title_block, subtitle_block, footer_block) for block, color in zip((title_block, subtitle_block, footer_block), colors): p.setPen(color) block.draw(p) p.end() img.setText('Generated cover', '%s %s' % (__appname__, __version__)) if as_qimage: return img return pixmap_to_data(img)
def _set_common_top_ui(self): top_frame = QFrame() top_frame.setMaximumHeight(60) top_layout = QVBoxLayout(top_frame) self.layout.addWidget(top_frame) common_top_frame = QFrame() common_top_frame.setMinimumHeight(50) common_top_frame.setMaximumHeight(50) common_top_layout = QHBoxLayout(common_top_frame) top_layout.addWidget(common_top_frame) common_top_layout.addStretch(0) label = QLabel(i18n[self.lang]['Type'] + ':') self.label_type = QLabel('') self.label_type.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_type) label = QLabel(i18n[self.lang]['Mode'] + ':') self.label_mode = QLabel('') self.label_mode.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_mode) label = QLabel(i18n[self.lang]['HardwareVersion'] + ':') self.label_hard_version = QLabel('') self.label_hard_version.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_hard_version) label = QLabel(i18n[self.lang]['FirmwareVersion'] + ':') self.label_firm_version = QLabel('') self.label_firm_version.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_firm_version) label_1 = QLabel(i18n[self.lang]['Connected'] + ':') self.label_connected = QLabel() img = QImage() self.label_connected.setMaximumHeight(20) self.label_connected.setMaximumWidth(20) self.label_connected.setScaledContents(True) if img.load(disconnect_icon_path): self.label_connected.setPixmap(QPixmap.fromImage(img)) self.lnt_addr = QLineEdit('COM12') self.lnt_addr.setMaximumWidth(50) self.lnt_addr.setMinimumWidth(30) self.btn_connect = QPushButton(i18n[self.lang]['Connect']) # self.btn_connect.setMaximumWidth(50) # common_top_layout.addStretch(0) common_top_layout.setSpacing(10) common_top_layout.addWidget(label_1) common_top_layout.addWidget(self.label_connected) common_top_layout.addWidget(self.lnt_addr) common_top_layout.addWidget(self.btn_connect)
def __init__(self): super().__init__() self.setupUi(self) map_api_server = "http://static-maps.yandex.ru/1.x/" map_params = {"l": "map", 'll': '1,1'} response = perform_request(map_api_server, params=map_params) image = QImage().fromData(response.content) pix_map = QPixmap().fromImage(image) self.map_label.setPixmap(pix_map)
def showImage(self): self.imageShow = self.image.convert("RGBA") data = self.imageShow.tobytes('raw', 'RGBA') img = QImage(data, self.imageShow.size[0], self.imageShow.size[1], QImage.Format_RGBA8888) self.pixmap = QPixmap.fromImage(img) self.label.setPixmap( self.pixmap.scaled(self.label.size(), QtCore.Qt.IgnoreAspectRatio)) self.label.setGeometry(200, 100, 900, 500)
def _load_texture(self, file, id): path = pt.join(self.IMAGE_PATH, file) img = QImage() if img.load(path): self.textures[id] = QGLWidget.convertToGLFormat(img) print(f'Texture {path} loaded...[OK]') else: print(f'Texture {path} loaded...[FAIL]')
def paste(self): clipboard = QApplication.clipboard() md = clipboard.mimeData() if md.hasImage(): img = QImage(md.imageData()) if not img.isNull(): self.undo_stack.push(Replace(img, _('Paste image'), self)) else: error_dialog(self, _('No image'), _( 'No image available in the clipboard'), show=True)
def _updateImage(self): """ Retrieve a new image from Nao. """ self._alImage = self._videoProxy.getImageRemote(self._imgClient) self._image = QImage( self._alImage[6], # Pixel array. self._alImage[0], # Width. self._alImage[1], # Height. QImage.Format_RGB888)
def get_qimage(self, image: np.ndarray): height, width, colors = image.shape bytesPerLine = 3 * width QImage = QtGui.QImage image = QImage(image.data, width, height, bytesPerLine, QImage.Format_RGB888) image = image.rgbSwapped() return image
def to_png(bmp): from PyQt5.Qt import QImage, QByteArray, QBuffer i = QImage() if not i.loadFromData(bmp): raise ValueError('Invalid image data') ba = QByteArray() buf = QBuffer(ba) buf.open(QBuffer.WriteOnly) i.save(buf, 'png') return ba.data()
def processPendingDatagrams(self): while self.udpSocket.hasPendingDatagrams(): datagram, host, port = self.udpSocket.readDatagram( self.udpSocket.pendingDatagramSize()) buf = QBuffer() b = buf.write(self.udpSocket.readAll()) buf.seek(buf.pos() - b) image = QImage() image.loadFromData(buf.buffer()) image.save(r"D:\test.png")
def __call__(self, canvas): if canvas.has_selection and canvas.selection_state.rect is not None: pimg = self.after_image img = self.after_image = QImage(canvas.current_image) rect = QRectF(*get_selection_rect(img, canvas.selection_state.rect, canvas.target)) p = QPainter(img) p.setRenderHint(p.SmoothPixmapTransform, True) p.drawImage(rect, pimg, QRectF(pimg.rect())) p.end() return self.after_image
def read_camera_image(self, cvimg): # 在QgraphicsScene上呈现检测结果图 height, width, depth = cvimg.shape cvimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB) cvimg = QImage(cvimg.data, width, height, width * depth, QImage.Format_RGB888) pix = QtGui.QPixmap.fromImage(cvimg) self.item = QGraphicsPixmapItem(pix) # 创建像素图元 self.scene = QGraphicsScene() # 创建场景 self.scene.addItem(self.item) self.graphicsView.setScene(self.scene) # 将场景添加至视图
def update_image(self, array: np.ndarray): im = cv2.transpose(array) im = im.transpose((1, 0, 2)).copy() image = QImage(im, im.shape[1], im.shape[0], QImage.Format_RGB888) palette = self.widget.palette() image = image.scaled(self.widget.geometry().width(), self.widget.geometry().height()) palette.setBrush(QPalette.Background, QBrush(image)) self.widget.setPalette(palette) self.widget.update()
def imageForUrl(cls, url, allowNull=False): ''' @param: url QUrl @return: QImage ''' if not url.path(): return allowNull and QImage() or cls.emptyWebImage() with cls.instance()._iconCacheMutex: encUrl = encodeUrl(url) # find in urlImageCache img = cls.instance()._urlImageCache.get(encUrl, None) if img: if not img.isNull(): return img if not allowNull: return cls.emptyWebImage() return img # find from icon buffer for url0, img in cls.instance()._iconBuffer: if encodeUrl(url0) == encUrl: return img # TODO: is it necessary to use escapeSqlGlobString escapedUrl = gVar.appTools.escapeSqlGlobString( encUrl.data().decode()) urlPattern = '%s*' % escapedUrl icon = IconsDbModel.select().filter( IconsDbModel.url.contains(urlPattern)).first() img = QImage() if icon: img.loadFromData(icon.icon) cls.instance()._urlImageCache[encUrl] = img if not img.isNull(): return img if not allowNull: return cls.emptyWebImage() return img
def blend_on_canvas(img, width, height, bgcolor='#ffffff'): ' Blend the `img` onto a canvas with the specified background color and size ' w, h = img.width(), img.height() scaled, nw, nh = fit_image(w, h, width, height) if scaled: img = img.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) w, h = nw, nh canvas = QImage(width, height, QImage.Format_RGB32) canvas.fill(QColor(bgcolor)) overlay_image(img, canvas, (width - w) // 2, (height - h) // 2) return canvas
def makeQImage(self, width, height): data = numpy.zeros((width, height), float) data[...] = (numpy.arange(width) / (width - 1.))[:, numpy.newaxis] # make brush image -- diag background, with colormap on top img = QImage(width, height, QImage.Format_RGB32) painter = QPainter(img) painter.fillRect(0, 0, width, height, QBrush(QColor("white"))) painter.fillRect(0, 0, width, height, QBrush(Qt.BDiagPattern)) painter.drawImage(0, 0, self.colorize(data)) painter.end() return img