Пример #1
0
    def save(self, filename, chart_size, legend_width=None):
        """ save graph as file
        """
        if not filename:
            """ if filename is not specified, open a save file dialog
            """
            filename = QFileDialog.getSaveFileName(None, 'Save File')[0]
            if not filename[-4:] in ['.png', '.jpg',]:
                """ TODO : cleaner extension manager
                """
                filename += ".png"
                
        image_size = chart_size
        
        if legend_width:
            image_size = image_size + QSize(legend_width, 0)

        image = QImage(image_size, QImage.Format_ARGB32_Premultiplied)
        painter = QPainter(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(image.rect(), Qt.white)
        self.draw(painter, QRect(QPoint(0, 0), chart_size))
        
        if legend_width:
            legendRect = QRect(QPoint(chart_size.width(), 10),
                               QSize(legend_width, chart_size.height()))
            self.draw_legend(painter, legendRect)
        painter.end()
        return image.save(filename)
Пример #2
0
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)
Пример #3
0
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)
Пример #4
0
 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.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')
Пример #5
0
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)
Пример #6
0
def image_from_data(data):
    if isinstance(data, QImage):
        return data
    i = QImage()
    if not i.loadFromData(data):
        raise ValueError('Not a valid image')
    return i
Пример #7
0
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('(\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
Пример #8
0
 def __init__ (self,database,progressBar,parent=None):
     super(Univers,self).__init__(parent)
     self.progress = progressBar
     self.factions = {}
     self.temples = {}
     self.database = database
     self.list_actions = {}
     self.cancelled_heros_id = []
     self.modifications = []
     self.loadFromFile()
     self.currentFaction = None
     self.currentEmpire = None
     self.currentKingdom= None
     self.currentGroupe= None     
     self.selected_Warriors = [[],[]]
     self.filtered_Warriors = []
     self.settings = Config().instance.settings
     colors =  self.settings.value ("global/groupe_color").split(",")
     self.groupe_color_icons = {}
     self.groupe_color_value = {}
     for color in colors :
         icon = QIcon(":textures/"+color)
         self.groupe_color_icons[color] = icon
         image = QImage(":textures/"+color)
         value = image.pixel(image.width()/2.0,image.height()/2.0)
         # pour view map donner une couleur a item warrior
         self.groupe_color_value[color]  = QColor(value)
Пример #9
0
def add_borders(img, left=0, top=0, right=0, bottom=0, border_color="#ffffff"):
    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(img, canvas, left, top)
    return canvas
Пример #10
0
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('(\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
Пример #11
0
    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)
Пример #12
0
 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.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')
Пример #13
0
    def saveImageButtonClicked(self):
        filters = 'Portable Network Graphics (*.png)'
        filters += ';;' + 'Joint Photographic Experts Group (*.jpg)'
        filters += ';;' + 'Windows Bitmap (*.bmp)'
        filters += ';;' + 'Tagged Image File Format (*.tiff)'
        
        filename = QFileDialog.getSaveFileName(
             caption='Save Image As',
             directory='ptchan_image.png',
             filter=filters,
             initialFilter='Portable Network Graphics (*.png)')
        
        # retrieve data from PTchan engine
        data_raw = self.engine.getFilmView().getData()
        data = array('f', data_raw) # this converts data into proper array

        # convert from float in [0.0,1.0] to bytes in [0,255]
        list = []
        for comp in data:
            list.append(int(255.0 * comp))

        # transform list of integers into byte array
        byte_array = array('B', list)
        
        image = QImage(
            byte_array.tostring(),
            self.engine.getFilmView().getWidth(),
            self.engine.getFilmView().getHeight(),
            QImage.Format_RGB888)

        # default mirrored() inverts vertical, exactly what is needed to transform
        # image data from OpenGL coord frame
        image.mirrored().save(filename[0])
Пример #14
0
    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)
Пример #15
0
 def __init__(self):
     pictureflow.FlowImages.__init__(self)
     self.num = 40000
     i1, i2 = QImage(300, 400, QImage.Format_RGB32), QImage(
         300, 400, QImage.Format_RGB32)
     i1.fill(Qt.green), i2.fill(Qt.blue)
     self.images = [i1, i2]
Пример #16
0
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
Пример #17
0
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
Пример #18
0
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
Пример #19
0
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
Пример #20
0
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
Пример #21
0
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
Пример #22
0
    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)
Пример #23
0
    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]')
Пример #24
0
 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)
Пример #25
0
 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()
Пример #26
0
def get_pixel_map():
    ' Get the order of pixels in QImage (RGBA or BGRA usually) '
    global _qimage_pixel_map
    if _qimage_pixel_map is None:
        i = QImage(1, 1, QImage.Format_ARGB32)
        i.fill(QColor(0, 1, 2, 3))
        raw = bytearray(i.constBits().asstring(4))
        _qimage_pixel_map = {c:raw.index(x) for c, x in zip('RGBA', b'\x00\x01\x02\x03')}
        _qimage_pixel_map = ''.join(sorted(_qimage_pixel_map, key=_qimage_pixel_map.get))
    return _qimage_pixel_map
Пример #27
0
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 bytes(ba.data())
Пример #28
0
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()
Пример #29
0
 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)
Пример #30
0
def blend_on_canvas(img, width, height, bgcolor="#ffffff"):
    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(img, canvas, (width - w) // 2, (height - h) // 2)
    return canvas
Пример #31
0
 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()
Пример #32
0
 def contrast_spinbox_value_changed(self):
     self.img_proc.set_contrast(self.ui.contrast_spinbox.value())
     self.ui_color.c_contrast_for_all.setValue(
         self.ui.contrast_spinbox.value())
     img_rgb = self.img.img_RGB()
     img_rgb = self.img_proc.compute_light_contrast(img_rgb)
     self.img.set_img_tmp(self.img.img_RGB2BGR(img_rgb))
     bytes_per_line = 3 * self.img.width
     self.q_img = QImage(self.img.img_tmp_RGB(), self.img.width,
                         self.img.height, bytes_per_line,
                         QImage.Format_RGB888)
Пример #33
0
 def btn_sel_photo_clicked(self):
     fileName = QFileDialog.getOpenFileName(self, caption="Select Photo", filter="Image Files (*.png *.jpg *.bmp)")
     if (len(fileName) is not 0):
         print(fileName[0])
     self.file_path = fileName[0]
     img = QImage(fileName[0])
     self.img = img.copy()
     self.setPhototoView(img)
     arr = fileName[0].split("/")
     index = len(arr) - 1
     self.lbl_photo_loc.setText(file_dir+"/"+arr[index])
Пример #34
0
    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)
Пример #35
0
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
Пример #36
0
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
Пример #37
0
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)
Пример #38
0
 def __init__(self, dirpath):
     pictureflow.FlowImages.__init__(self)
     self.images = []
     self.captions = []
     self.subtitles = []
     for f in os.listdir(dirpath):
         f = os.path.join(dirpath, f)
         img = QImage(f)
         if not img.isNull():
             self.images.append(img)
             self.captions.append(os.path.basename(f))
             self.subtitles.append('%d bytes'%os.stat(f).st_size)
Пример #39
0
def message_image(text, width=500, height=400, font_size=20):
    init_environment()
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(Qt.white)
    p = QPainter(img)
    f = QFont()
    f.setPixelSize(font_size)
    p.setFont(f)
    r = img.rect().adjusted(10, 10, -10, -10)
    p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text)
    p.end()
    return pixmap_to_data(img)
Пример #40
0
def message_image(text, width=500, height=400, font_size=20):
    init_environment()
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(Qt.white)
    p = QPainter(img)
    f = QFont()
    f.setPixelSize(font_size)
    p.setFont(f)
    r = img.rect().adjusted(10, 10, -10, -10)
    p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text)
    p.end()
    return pixmap_to_data(img)
Пример #41
0
 def load_image(self):
     fname = QFileDialog.getOpenFileName(self.main_ui.window, 'Open file',
                                         '', '*.svg')
     if fname and fname[0]:
         img = QImage()
         if img.load(fname[0]):
             self.label_img.setPixmap(QPixmap.fromImage(img))
             with open(fname[0], 'rb') as f:
                 self.handler.source = f.read()
                 self.handler.template = None
                 self.gcode = None
                 self.up_frame.show()
Пример #42
0
def load_jxr_data(data):
    with TemporaryDirectory() as tdir:
        if iswindows and isinstance(tdir, type('')):
            tdir = tdir.encode('mbcs')
        with lopen(os.path.join(tdir, 'input.jxr'), 'wb') as f:
            f.write(data)
        cmd = [get_exe_path('JxrDecApp'), '-i', 'input.jxr', '-o', 'output.tif', '-c', '0']
        creationflags = 0x08 if iswindows else 0
        subprocess.Popen(cmd, cwd=tdir, stdout=lopen(os.devnull, 'wb'), stderr=subprocess.STDOUT, creationflags=creationflags).wait()
        i = QImage()
        if not i.load(os.path.join(tdir, 'output.tif')):
            raise NotImage('Failed to convert JPEG-XR image')
        return i
Пример #43
0
def getImage(name: str, get_null: bool = False) -> QImage:
    """PNG image called name in assets."""

    if name in imageResources:
        return imageResources[name]
    else:
        resource = QImage(os.path.join(wd, "assets", name + ".png"))
        if resource.isNull():
            if not get_null:
                raise ValueError(f"Resource {name}.png doesn't exist")
        else:
            imageResources[name] = resource
        return resource
Пример #44
0
    def dialog_color_compute(self):
        if self.ui_color.l_radio_all_bands.isChecked():
            self.img_proc.set_light(self.ui_color.l_spin_light_for_all.value())
            self.ui_color.l_spin_red.setValue(
                self.ui_color.l_spin_light_for_all.value())
            self.ui_color.l_spin_green.setValue(
                self.ui_color.l_spin_light_for_all.value())
            self.ui_color.l_spin_blue.setValue(
                self.ui_color.l_spin_light_for_all.value())
            self.ui.light_spinbox.setValue(
                self.ui_color.l_spin_light_for_all.value())
            img_rgb = self.img.img_RGB()
            img_rgb = self.img_proc.compute_light_contrast(img_rgb)
            self.img.set_img_tmp(self.img.img_RGB2BGR(img_rgb))

        if self.ui_color.c_radio_all_bands.isChecked():
            self.img_proc.set_contrast(self.ui.contrast_spinbox.value())
            self.ui.contrast_spinbox.setValue(
                self.ui_color.c_contrast_for_all.value())
            self.ui_color.c_double_spin_red.setValue(
                self.ui_color.c_contrast_for_all.value())
            self.ui_color.c_double_spin_green.setValue(
                self.ui_color.c_contrast_for_all.value())
            self.ui_color.c_double_spin_blue.setValue(
                self.ui_color.c_contrast_for_all.value())
            img_rgb = self.img.img_RGB()
            img_rgb = self.img_proc.compute_light_contrast(img_rgb)
            self.img.set_img_tmp(self.img.img_RGB2BGR(img_rgb))

        if self.ui_color.l_radio_rgb.isChecked(
        ) or self.ui_color.c_radio_rgb.isChecked():
            self.img_proc.set_light_contrast_rgb(
                self.ui_color.l_spin_red.value(),
                self.ui_color.l_spin_green.value(),
                self.ui_color.l_spin_blue.value(),
                self.ui_color.c_double_spin_red.value(),
                self.ui_color.c_double_spin_green.value(),
                self.ui_color.c_double_spin_blue.value())
            img_rgb = self.img.img_RGB()
            img_rgb = self.img_proc.compute_light_contrast_per_channel(img_rgb)
            self.img.set_img_tmp(self.img.img_RGB2BGR(img_rgb))
            bytes_per_line = 3 * self.img.width
            self.q_img = QImage(self.img.img_tmp_RGB(), self.img.width,
                                self.img.height, bytes_per_line,
                                QImage.Format_RGB888)
            self.img_proc.compute_light_contrast_per_channel(self.img.img_tmp)

        bytes_per_line = 3 * self.img.width
        self.q_img = QImage(self.img.img_tmp_RGB(), self.img.width,
                            self.img.height, bytes_per_line,
                            QImage.Format_RGB888)
Пример #45
0
    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')
            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, self.delegate.cover_size.width(),
                        self.delegate.cover_size.height())
                    if scaled:
                        if self.ignore_render_requests.is_set():
                            return
                        p = p.scaled(nwidth, nheight, Qt.IgnoreAspectRatio,
                                     Qt.SmoothTransformation)
                    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)
Пример #46
0
 def load_image(self, data):
     self.is_valid = False
     try:
         fmt = identify_data(data)[-1].encode('ascii')
     except Exception:
         fmt = b''
     self.original_image_format = fmt.decode('ascii').lower()
     self.selection_state.reset()
     self.original_image_data = data
     self.current_image = i = self.original_image = (
         QImage.fromData(data, format=fmt) if fmt else QImage.fromData(data))
     self.is_valid = not i.isNull()
     self.update()
     self.image_changed.emit(self.current_image)
Пример #47
0
def encode_jpeg(file_path, quality=80):
    from calibre.utils.speedups import ReadOnlyFileBuffer
    quality = max(0, min(100, int(quality)))
    exe = get_exe_path('cjpeg')
    cmd = [exe] + '-optimize -progressive -maxmemory 100M -quality'.split() + [str(quality)]
    img = QImage()
    if not img.load(file_path):
        raise ValueError('%s is not a valid image file' % file_path)
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    if not img.save(buf, 'PPM'):
        raise ValueError('Failed to export image to PPM')
    return run_optimizer(file_path, cmd, as_filter=True, input_data=ReadOnlyFileBuffer(ba.data()))
Пример #48
0
 def load_image(self, data):
     self.is_valid = False
     try:
         fmt = identify_data(data)[-1].encode('ascii')
     except Exception:
         fmt = b''
     self.original_image_format = fmt.decode('ascii').lower()
     self.selection_state.reset()
     self.original_image_data = data
     self.current_image = i = self.original_image = (QImage.fromData(
         data, format=fmt) if fmt else QImage.fromData(data))
     self.is_valid = not i.isNull()
     self.update()
     self.image_changed.emit(self.current_image)
Пример #49
0
def get_pixel_map():
    ' Get the order of pixels in QImage (RGBA or BGRA usually) '
    global _qimage_pixel_map
    if _qimage_pixel_map is None:
        i = QImage(1, 1, QImage.Format_ARGB32)
        i.fill(QColor(0, 1, 2, 3))
        raw = bytearray(i.constBits().asstring(4))
        _qimage_pixel_map = {
            c: raw.index(x)
            for c, x in zip('RGBA', b'\x00\x01\x02\x03')
        }
        _qimage_pixel_map = ''.join(
            sorted(_qimage_pixel_map, key=_qimage_pixel_map.get))
    return _qimage_pixel_map
Пример #50
0
 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.SmoothPixmapTransform)
     painter.drawImage(rect, logo)
     return self.ccolor1, self.ccolor1, self.ccolor1
Пример #51
0
def create_icon(text, palette=None, sz=32, divider=2):
    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)
    qDrawShadeRect(p, img.rect(), palette, fill=QColor('#ffffff'), lineWidth=1, midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(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))
Пример #52
0
 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 = bytes(ba.data())
     except Exception as e:
         self.exception = e
         self.traceback = traceback.format_exc()
     finally:
         self.loop.exit(0)
Пример #53
0
 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()
Пример #54
0
 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.SmoothPixmapTransform)
     painter.drawImage(rect, logo)
     return self.ccolor1, self.ccolor1, self.ccolor1
Пример #55
0
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()
Пример #56
0
def qimage_to_magick(img):
    ans = Image()
    fmt = get_pixel_map()
    if not img.hasAlphaChannel():
        if img.format() != img.Format_RGB32:
            img = QImage(img)
            img.setFormat(QImage.Format_RGB32)
        fmt = fmt.replace('A', 'P')
    else:
        if img.format() != img.Format_ARGB32:
            img = QImage(img)
            img.setFormat(img.Format_ARGB32)
    raw = img.constBits().ascapsule()
    ans.constitute(img.width(), img.height(), fmt, raw)
    return ans
Пример #57
0
    def start_show_animation(self):
        if self.rendered_pixmap is not None:
            return

        dpr = getattr(self, 'devicePixelRatioF', self.devicePixelRatio)()
        p = QImage(dpr * self.size(), QImage.Format_ARGB32_Premultiplied)
        p.setDevicePixelRatio(dpr)
        self.render(p)
        self.rendered_pixmap = QPixmap.fromImage(p)
        self.original_visibility = v = []
        for child in self.findChildren(QWidget):
            if child.isVisible():
                child.setVisible(False)
                v.append(child)
        self.show_animation.start()
Пример #58
0
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
Пример #59
0
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