Esempio n. 1
0
 def __init__(self, a, r, g, b):
     nx, ny = r.shape
     argb = (a << 24) | (r << 16) | (g << 8) | b
     # transpose array, as it is in column-major (C order), while QImages are in row-major order
     dprint(5, "making qimage of size", nx, ny)
     self._buffer = argb.transpose().tostring()
     QImage.__init__(self, self._buffer, nx, ny, QImage.Format_ARGB32)
Esempio n. 2
0
 def __init__(self, a, r, g, b):
     nx, ny = r.shape
     argb = (a << 24) | (r << 16) | (g << 8) | b
     # transpose array, as it is in column-major (C order), while QImages are in row-major order
     dprint(5, "making qimage of size", nx, ny)
     self._buffer = argb.transpose().tostring()
     QImage.__init__(self, self._buffer, nx, ny, QImage.Format_ARGB32)
Esempio n. 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)
Esempio n. 4
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)
Esempio n. 5
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]
    def ThresholdValChange(self):
        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = self.srcImage.pixelIndex(i, j)
                if (temp >= self.thresholdSpinBox.value()):
                    self.grayImage.setPixel(i, j, 255)
                else:
                    self.grayImage.setPixel(i, j, 0)
        self.resultImage = QImage(self.grayImage)
        #如果选中了只雕刻轮廓
        if self.chooseBox.isChecked():
            img = np.zeros(
                (self.grayImage.height(), self.grayImage.width(), 1), np.uint8)
            for i in range(self.grayImage.width()):
                for j in range(self.grayImage.height()):
                    img[j, i] = self.grayImage.pixelIndex(i, j)
            #提取轮廓
            contours = cv.findContours(img, cv.RETR_LIST,
                                       cv.CHAIN_APPROX_SIMPLE)
            img = np.zeros(
                (self.grayImage.height(), self.grayImage.width(), 1), np.uint8)
            cv.drawContours(img, contours[1][:-1], -1, (255, 255, 255),
                            self.ContoursWidthSpinBox.value())
            #转换轮廓到显示界面
            for i in range(self.resultImage.width()):
                for j in range(self.resultImage.height()):
                    if img[j, i] == 0:
                        self.resultImage.setPixel(i, j, 255)
                    else:
                        self.resultImage.setPixel(i, j, 0)

        self.imageLabel.setPixmap(QPixmap(self.resultImage))
Esempio n. 7
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)
Esempio n. 8
0
 def cover(self, path, as_file=False, as_image=False,
         as_path=False):
     path = os.path.join(self.library_path, path, 'cover.jpg')
     ret = None
     if os.access(path, os.R_OK):
         try:
             f = lopen(path, 'rb')
         except (IOError, OSError):
             time.sleep(0.2)
             f = lopen(path, 'rb')
         with f:
             if as_path:
                 pt = PersistentTemporaryFile('_dbcover.jpg')
                 with pt:
                     shutil.copyfileobj(f, pt)
                 return pt.name
             if as_file:
                 ret = SpooledTemporaryFile(SPOOL_SIZE)
                 shutil.copyfileobj(f, ret)
                 ret.seek(0)
             else:
                 ret = f.read()
                 if as_image:
                     from PyQt4.Qt import QImage
                     i = QImage()
                     i.loadFromData(ret)
                     ret = i
     return ret
Esempio n. 9
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(b'%íì¦"')
     creator = ('%s %s [http://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')
Esempio n. 10
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(b'%íì¦"')
     creator = ('%s %s [http://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')
Esempio n. 11
0
 def cover(self, path, as_file=False, as_image=False, as_path=False):
     path = os.path.join(self.library_path, path, 'cover.jpg')
     ret = None
     if os.access(path, os.R_OK):
         try:
             f = lopen(path, 'rb')
         except (IOError, OSError):
             time.sleep(0.2)
             f = lopen(path, 'rb')
         with f:
             if as_path:
                 pt = PersistentTemporaryFile('_dbcover.jpg')
                 with pt:
                     shutil.copyfileobj(f, pt)
                 return pt.name
             if as_file:
                 ret = SpooledTemporaryFile(SPOOL_SIZE)
                 shutil.copyfileobj(f, ret)
                 ret.seek(0)
             else:
                 ret = f.read()
                 if as_image:
                     from PyQt4.Qt import QImage
                     i = QImage()
                     i.loadFromData(ret)
                     ret = i
     return ret
Esempio n. 12
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)
Esempio n. 13
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
Esempio n. 14
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
Esempio n. 15
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)
Esempio n. 16
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)
Esempio n. 17
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()
Esempio n. 18
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)
Esempio n. 19
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)
Esempio n. 20
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)
Esempio n. 21
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))
Esempio n. 22
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()
Esempio n. 23
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)
Esempio n. 24
0
 def __call__(self, ok):
     from PyQt4.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)
Esempio n. 25
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)
Esempio n. 26
0
    def __init__(
        self,
        file_object,
        page_width,
        page_height,
        left_margin,
        top_margin,
        right_margin,
        bottom_margin,
        width,
        height,
        errors=print,
        debug=print,
        compress=True,
    ):
        QPaintEngine.__init__(self, self.features)
        self.file_object = file_object
        self.compress = compress
        self.page_height, self.page_width = page_height, page_width
        self.left_margin, self.top_margin = left_margin, top_margin
        self.right_margin, self.bottom_margin = right_margin, bottom_margin
        self.pixel_width, self.pixel_height = width, height
        # Setup a co-ordinate transform that allows us to use co-ords
        # from Qt's pixel based co-ordinate system with its origin at the top
        # left corner. PDF's co-ordinate system is based on pts and has its
        # origin in the bottom left corner. We also have to implement the page
        # margins. Therefore, we need to translate, scale and reflect about the
        # x-axis.
        dy = self.page_height - self.top_margin
        dx = self.left_margin
        sx = (self.page_width - self.left_margin - self.right_margin) / self.pixel_width
        sy = (self.page_height - self.top_margin - self.bottom_margin) / self.pixel_height

        self.pdf_system = QTransform(sx, 0, 0, -sy, dx, dy)
        self.do_stroke = True
        self.do_fill = False
        self.scale = sqrt(sy ** 2 + sx ** 2)
        self.xscale, self.yscale = sx, sy
        self.graphics_state = GraphicsState()
        self.errors_occurred = False
        self.errors, self.debug = errors, debug
        self.text_option = QTextOption()
        self.text_option.setWrapMode(QTextOption.NoWrap)
        self.fonts = {}
        i = QImage(1, 1, QImage.Format_ARGB32)
        i.fill(qRgba(0, 0, 0, 255))
        self.alpha_bit = i.constBits().asstring(4).find(b"\xff")
        self.current_page_num = 1
        self.current_page_inited = False
Esempio n. 27
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
Esempio n. 28
0
def magick_to_qimage(img):
    fmt = get_pixel_map()
    # ImageMagick can output only output raw data in some formats that can be
    # read into QImage directly, if the QImage format is not one of those, use
    # PNG
    if fmt in {'RGBA', 'BGRA'}:
        w, h = img.size
        img.depth = 8  # QImage expects 8bpp
        raw = img.export(fmt)
        i = QImage(raw, w, h, QImage.Format_ARGB32)
        del raw  # According to the documentation, raw is supposed to not be deleted, but it works, so make it explicit
        return i
    else:
        raw = img.export('PNG')
        return QImage.fromData(QByteArray(raw), 'PNG')
Esempio n. 29
0
    def __init__(self, parent = None):
        '''
        Constructor
        '''
        super(VoivoiShow, self).__init__(parent)
        #self.setStyleSheet("background: #000;")
        
        self.splashscreen = QImage("res/splashscreen.jpg")
        #print(self.splashscreen.isNull())
        if not self.splashscreen.isNull():
            self.imgList.append(self.splashscreen)
                                      
        self.imageLabel = QLabel()
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setParent(self)

        self.httpPool = urllib3.PoolManager()
        
        self.slideIterator = 0
        self.timer.timeout.connect(self.nextImage)
        self.updateTimer = QTimer()
        self.updateTimer.timeout.connect(self.updateImages)
        self.mostRecent = datetime.fromtimestamp(0)
        
        self.layout = QHBoxLayout()
        self.layout.setMargin(0)
        self.layout.addWidget(self.imageLabel)
        self.layout.setAlignment(self.imageLabel, Qt.AlignHCenter)
        self.setLayout(self.layout)
        self.voivoifont = QFont("Helvetica", 48)
        self.voivoifont.setBold(True)
Esempio n. 30
0
 def __call__(self, ok):
     from PyQt4.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)
Esempio n. 31
0
 def failed_img(self):
     if self._failed_img is None:
         i = QImage(200, 150, QImage.Format_ARGB32)
         i.fill(Qt.white)
         p = QPainter(i)
         r = i.rect().adjusted(10, 10, -10, -10)
         n = QPen(Qt.DashLine)
         n.setColor(Qt.black)
         p.setPen(n)
         p.drawRect(r)
         p.setPen(Qt.black)
         f = self.font()
         f.setPixelSize(20)
         p.setFont(f)
         p.drawText(r.adjusted(10, 0, -10, 0), Qt.AlignCenter | Qt.TextWordWrap, _('Image could not be rendered'))
         p.end()
         self._failed_img = QPixmap.fromImage(i)
     return self._failed_img
Esempio n. 32
0
 def current_page_image(self, overlap=-1):
     if overlap < 0:
         overlap = self.height()
     img = QImage(self.width(), overlap, QImage.Format_ARGB32_Premultiplied)
     painter = QPainter(img)
     painter.setRenderHints(self.renderHints())
     self.document.mainFrame().render(painter, QRegion(0, 0, self.width(), overlap))
     painter.end()
     return img
Esempio n. 33
0
 def __call__(self, container):
     from PyQt4.Qt import QImage
     from calibre.gui2 import pixmap_to_data
     ext = container.mime_map[self.name].split('/')[-1].upper()
     if ext == 'JPG':
         ext = 'JPEG'
     if ext not in ('PNG', 'JPEG', 'GIF'):
         return False
     with container.open(self.name, 'r+b') as f:
         raw = f.read()
         i = QImage()
         i.loadFromData(raw)
         if i.isNull():
             return False
         raw = pixmap_to_data(i, format=ext, quality=95)
         f.seek(0)
         f.truncate()
         f.write(raw)
     return True
Esempio n. 34
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)
Esempio n. 35
0
 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
Esempio n. 36
0
def to_png(bmp):
    # ImageMagick does not convert some bmp files correctly, while Qt does,
    # so try Qt first. See for instance:
    # https://bugs.launchpad.net/calibre/+bug/934167
    # ImageMagick bug report:
    # http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=20350
    from PyQt4.Qt import QImage, QByteArray, QBuffer
    i = QImage()
    if i.loadFromData(bmp):
        ba = QByteArray()
        buf = QBuffer(ba)
        buf.open(QBuffer.WriteOnly)
        i.save(buf, 'png')
        return bytes(ba.data())

    from calibre.utils.magick import Image
    img = Image()
    img.load(bmp)
    return img.export('png')
Esempio n. 37
0
 def __call__(self, container):
     from PyQt4.Qt import QImage
     from calibre.gui2 import pixmap_to_data
     ext = container.mime_map[self.name].split('/')[-1].upper()
     if ext == 'JPG':
         ext = 'JPEG'
     if ext not in ('PNG', 'JPEG', 'GIF'):
         return False
     with container.open(self.name, 'r+b') as f:
         raw = f.read()
         i = QImage()
         i.loadFromData(raw)
         if i.isNull():
             return False
         raw = pixmap_to_data(i, format=ext, quality=95)
         f.seek(0)
         f.truncate()
         f.write(raw)
     return True
Esempio n. 38
0
 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
Esempio n. 39
0
File: test.py Progetto: sss/calibre
def main():
    app = QApplication([])
    app
    tdir = os.path.abspath('.')
    pdf = os.path.join(tdir, 'painter.pdf')
    func = full
    dpi = 100
    with open(pdf, 'wb') as f:
        dev = PdfDevice(f, xdpi=dpi, ydpi=dpi, compress=False)
        img = QImage(dev.width(), dev.height(),
                     QImage.Format_ARGB32_Premultiplied)
        img.setDotsPerMeterX(dpi * 39.37)
        img.setDotsPerMeterY(dpi * 39.37)
        img.fill(Qt.white)
        run(dev, func)
    run(img, func)
    path = os.path.join(tdir, 'painter.png')
    img.save(path)
    print('PDF written to:', pdf)
    print('Image written to:', path)
Esempio n. 40
0
 def failed_img(self):
     if self._failed_img is None:
         i = QImage(200, 150, QImage.Format_ARGB32)
         i.fill(Qt.white)
         p = QPainter(i)
         r = i.rect().adjusted(10, 10, -10, -10)
         n = QPen(Qt.DashLine)
         n.setColor(Qt.black)
         p.setPen(n)
         p.drawRect(r)
         p.setPen(Qt.black)
         f = self.font()
         f.setPixelSize(20)
         p.setFont(f)
         p.drawText(r.adjusted(10, 0, -10, 0),
                    Qt.AlignCenter | Qt.TextWordWrap,
                    _('Image could not be rendered'))
         p.end()
         self._failed_img = QPixmap.fromImage(i)
     return self._failed_img
Esempio n. 41
0
 def updateImages(self, buffer_limit=20):
     try:
         db_connection = pymysql.connect(self.host, self.user, self.passwd, self.db)
     except: 
         print("Database connection not available")
         return
     
     sqlquery = "SELECT `categoryOrder`, `userID`, `dayID`, `comment`, `timestamp`, `eventID` FROM `pictures` WHERE `eventID`>=" + str(self.eventID) + " AND `timestamp`>'" + str(self.mostRecent) + "' ORDER BY `timestamp` ASC"
     #print(sqlquery)
     try:
         with db_connection.cursor() as cursor:
             cursor.execute(sqlquery)
             
             result = cursor.fetchall()
             
             for entry in result:
                 print(entry[4])
                 #print(self.mostRecent)
                 if entry[4] > self.mostRecent:
                     if entry[0] == 0:
                         print("BREAKING")
                         continue
                     self.mostRecent = entry[4]
                     image_url = "http://voivoi.eventfive.de/events/" + str(entry[5]) + "/uploads/" + str(entry[0]) + "_" + str(entry[1]) + "_" + str(entry[2]) + ".jpg"
                     req = self.httpPool.request('GET',image_url)
                     if req.status == 200:
                         data = req.data
                         print("Newer file downloaded")
                             
                         might_be_image = QImage()
                         if might_be_image.loadFromData(data) :
                             #print("URL is valid")
                             self.drawOverlay(might_be_image, entry)
                         
                             if len(self.imgList) > buffer_limit-1: #TODO: change behaviour to iteration over fixed list, to prevent jumps
                                 self.imgList.pop(1)
                             self.imgList.append(might_be_image)
                            
     finally: 
         print("Update done, closing connection")
         db_connection.close()
Esempio n. 42
0
def to_png(bmp):
    # ImageMagick does not convert some bmp files correctly, while Qt does,
    # so try Qt first. See for instance:
    # https://bugs.launchpad.net/calibre/+bug/934167
    # ImageMagick bug report:
    # http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=20350
    from PyQt4.Qt import QImage, QByteArray, QBuffer

    i = QImage()
    if i.loadFromData(bmp):
        ba = QByteArray()
        buf = QBuffer(ba)
        buf.open(QBuffer.WriteOnly)
        i.save(buf, "png")
        return bytes(ba.data())

    from calibre.utils.magick import Image

    img = Image()
    img.load(bmp)
    return img.export("png")
 def handleStartButton(self):
     if self.iconList.count() < 2:
         rm = str(self.media.currentTime() / 100.00 / 10.00)
         item = QListWidgetItem()
         img = QImage(self.video.snapshot())
         pix = QtGui.QPixmap.fromImage(img)
         item.setIcon(QIcon(pix))
         item.setText("Start: " + rm)
         self.iconList.addItem(item)
         self.videoCuts.append(rm)
     else:
         return
Esempio n. 44
0
    def dropEvent(self, event):
        event.setDropAction(Qt.CopyAction)
        md = event.mimeData()

        x, y = dnd_get_image(md)
        if x is not None:
            # We have an image, set cover
            event.accept()
            if y is None:
                # Local image
                self.undo_stack.push(Replace(x.toImage(), _('Drop image'), self))
            else:
                d = DownloadDialog(x, y, self.gui)
                d.start_download()
                if d.err is None:
                    with open(d.fpath, 'rb') as f:
                        img = QImage()
                        img.loadFromData(f.read())
                    if not img.isNull():
                        self.undo_stack.push(Replace(img, _('Drop image'), self))

        event.accept()
Esempio n. 45
0
def qimage_to_magick(img):
    ans = Image()
    if isosx:
        # For some reson, on OSX MagickConstituteImage fails, and I can't be
        # bothered figuring out why. Dumping to uncompressed PNG is reasonably
        # fast.
        raw = pixmap_to_data(img, 'PNG', quality=100)
        ans.load(raw)
        return ans
    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
Esempio n. 46
0
 def configureSponsorButton(self, btn):
     """
     Load the image in the Sponsor button I{btn} that is displayed at the 
     top of the Property Manager.
     
     @param btn: The sponsor button.
     @type  btn: QToolButton
     """
     qimg = QImage(self.imgfile)
     pixmap = QPixmap.fromImage(qimg)
     size = QSize(pixmap.width(), pixmap.height())
     btn.setIconSize(size)
     btn.setIcon(QIcon(pixmap))
Esempio n. 47
0
    def dropEvent(self, event):
        event.setDropAction(Qt.CopyAction)
        md = event.mimeData()

        x, y = dnd_get_image(md)
        if x is not None:
            # We have an image, set cover
            event.accept()
            if y is None:
                # Local image
                self.undo_stack.push(Replace(x.toImage(), _('Drop image'), self))
            else:
                d = DownloadDialog(x, y, self.gui)
                d.start_download()
                if d.err is None:
                    with open(d.fpath, 'rb') as f:
                        img = QImage()
                        img.loadFromData(f.read())
                    if not img.isNull():
                        self.undo_stack.push(Replace(img, _('Drop image'), self))

        event.accept()
Esempio n. 48
0
    def _repr_png_(self):

        self._widget.hide()

        QtGui.QApplication.processEvents()

        try:
            self.image = QImage(self._widget.viewRect().size().toSize(),
                                QImage.Format_RGB32)
        except AttributeError:
            self._widget.updateGL()
            self.image = self._widget.grabFrameBuffer()

        painter = QPainter(self.image)
        self._widget.render(painter)

        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        buffer.open(QIODevice.ReadWrite)
        self.image.save(buffer, 'PNG')
        buffer.close()

        return bytes(byte_array)
Esempio n. 49
0
    def cover(self, book_id,
            as_file=False, as_image=False, as_path=False):
        '''
        Return the cover image or None. By default, returns the cover as a
        bytestring.

        WARNING: Using as_path will copy the cover to a temp file and return
        the path to the temp file. You should delete the temp file when you are
        done with it.

        :param as_file: If True return the image as an open file object (a SpooledTemporaryFile)
        :param as_image: If True return the image as a QImage object
        :param as_path: If True return the image as a path pointing to a
                        temporary file
        '''
        if as_file:
            ret = SpooledTemporaryFile(SPOOL_SIZE)
            if not self.copy_cover_to(book_id, ret):
                return
            ret.seek(0)
        elif as_path:
            pt = PersistentTemporaryFile('_dbcover.jpg')
            with pt:
                if not self.copy_cover_to(book_id, pt):
                    return
            ret = pt.name
        else:
            buf = BytesIO()
            if not self.copy_cover_to(book_id, buf):
                return
            ret = buf.getvalue()
            if as_image:
                from PyQt4.Qt import QImage
                i = QImage()
                i.loadFromData(ret)
                ret = i
        return ret
Esempio n. 50
0
    def cover(self, book_id, as_file=False, as_image=False, as_path=False):
        '''
        Return the cover image or None. By default, returns the cover as a
        bytestring.

        WARNING: Using as_path will copy the cover to a temp file and return
        the path to the temp file. You should delete the temp file when you are
        done with it.

        :param as_file: If True return the image as an open file object (a SpooledTemporaryFile)
        :param as_image: If True return the image as a QImage object
        :param as_path: If True return the image as a path pointing to a
                        temporary file
        '''
        if as_file:
            ret = SpooledTemporaryFile(SPOOL_SIZE)
            if not self.copy_cover_to(book_id, ret):
                return
            ret.seek(0)
        elif as_path:
            pt = PersistentTemporaryFile('_dbcover.jpg')
            with pt:
                if not self.copy_cover_to(book_id, pt):
                    return
            ret = pt.name
        else:
            buf = BytesIO()
            if not self.copy_cover_to(book_id, buf):
                return
            ret = buf.getvalue()
            if as_image:
                from PyQt4.Qt import QImage
                i = QImage()
                i.loadFromData(ret)
                ret = i
        return ret
Esempio n. 51
0
    def init(self):
        if not self.__initialized__:
            self.__initialized__ = True

            if self.img:
                self.imgV = QImage(self.img)
                assert not self.imgV.isNull()

                if self.width is None:
                    self.width = self.imgV.width()
                if self.height is None:
                    self.height = self.imgV.height()

                self.textureId = self.importTexture(self.imgV)

                if self.imgoff:
                    self.imgoffV = QImage(self.imgoff)
                    self.textureOffId = self.importTexture(self.imgoffV)

            self.__defaulttoggled = self.toggled
            self.__defaultenabled = self.enabled
        else:
            self.toggled = self.__defaulttoggled
            self.enabled = self.__defaultenabled
 def handleEndButton(self):
     if self.iconList.count() < 2:
         rm = str(self.media.currentTime() / 100.00 / 10.00)
         item = QListWidgetItem()
         #item.setSizeHint(QSize(150, 40))
         img = QImage(self.video.snapshot())
         pix = QtGui.QPixmap.fromImage(img)
         item.setIcon(QIcon(pix))
         item.setText("End: " + rm)
         self.iconList.addItem(item)
         self.videoCuts.append(rm)
         self.t3 = float(str(self.media.remainingTime()))
         print(self.t3)
         self.media.stop()
         self.playbutton.setText('Play')
     else:
         return
    def LoadImageButtonClicked(self):
        self.filePath = QFileDialog.getOpenFileName(self, u"选择图片文件", "",
                                                    "Images (*.bmp)")
        if self.filePath == "":
            QMessageBox.warning(self, u"发生错误", u"没有选择可以识别的文件!!")
            return

        self.srcImage = QImage(self.filePath)
        self.grayImage = QImage(self.srcImage.size(), QImage.Format_Indexed8)

        for i in range(256):
            self.grayImage.setColor(i, qRgb(i, i, i))

        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = qGray(self.srcImage.pixel(i, j))
                self.grayImage.setPixel(i, j, temp)

        self.srcImage = QImage(self.grayImage)
        self.resultImage = QImage(self.grayImage)
        self.imageLabel.setPixmap(QPixmap(self.srcImage))