Beispiel #1
0
 def prep_image(self):
     """
     Prepare the image to be displayed on screen.
     """
     QImageReader.supportedImageFormats()
     self.original = image_tools.prepare_image(self.path, self)
     self.display_properties()
     self.to_display = self.original.copy()
     self.before_filter = self.original.copy()
     self.cache_colors = image_tools.get_modes(self.original)
     self.original_alpha = self.original.getchannel("A").copy()
     self.qt_tweaks()
     self.adjust_size()
     self.set_pixmap()          
    def __init__(self, *__args):
        if not self.supported_image_formats:
            self.supported_image_formats = [
                f.data().decode('utf-8')
                for f in QImageReader.supportedImageFormats()
            ]

        super().__init__(*__args)
Beispiel #3
0
 def test(h: bytes, f: BinaryIO) -> Optional[str]:
     if check(h, f):
         if hasattr(test, "checked"):
             return name
         if name in QImageReader.supportedImageFormats():
             setattr(test, "checked", True)
             return name
         imghdr.tests.remove(test)
     return None
Beispiel #4
0
	def fileOpen(self):
		if not self.okToContinue():
			return
		dir = os.path.dirname(self.filename) if self.filename is not None else '.'
		formats = ['{0}'.format(str(format).lower()) for format in QImageReader.supportedImageFormats()]
		formats = ['*.{0}'.format(format[2:5]) for format in formats]
		fname,_ = QFileDialog.getOpenFileName(self, 'Image Editor - Choose Image', dir, 'Image File ({0})'.format(" ".join(formats)))
		if fname:
			self.loadFile(fname)
Beispiel #5
0
 def test(h: bytes, f: Optional[BinaryIO]) -> Optional[str]:
     if check(h, f):
         if hasattr(test, "checked"):
             return name
         if (name in QImageReader.supportedImageFormats()
                 or name in imagereader.external_handler):
             setattr(test, "checked", True)
             return name
         imghdr.tests.remove(test)
     return None
Beispiel #6
0
 def dragEnterEvent(self, event):
     mimeData = event.mimeData()
     if mimeData.hasUrls():
         paths = mimeData.urls()
         path = paths[0].toLocalFile()
         ext = os.path.splitext(path)[1][1:]
         if ext.lower() in QImageReader.supportedImageFormats():
             event.acceptProposedAction()
     else:
         super().dragEnterEvent(event)
Beispiel #7
0
def qtInfo():
    """Returns Qt/PyQt information.
    """

    return {"Qt/PyQt information":{
                "Qt version": QT_VERSION_STR,
                "PyQt version": PYQT_VERSION_STR,
                "SIP version": SIP_VERSION_STR,
                "Qt library paths": QApplication.libraryPaths(),
                "Qt database plugins":  QSqlDatabase.drivers(),
                "Qt image plugins": QImageReader.supportedImageFormats()}}
Beispiel #8
0
 def dragEnterEvent(self, event):
     mimeData = event.mimeData()
     if mimeData.hasUrls():
         url = mimeData.urls()[0]
         if url.isLocalFile():
             path = url.toLocalFile()
             ext = os.path.splitext(path)[1][1:]
             if ext.lower() in QImageReader.supportedImageFormats():
                 event.acceptProposedAction()
         return
     super().dragEnterEvent(event)
Beispiel #9
0
 def fileOpen(self):
     if not self.okToContinue():
         return
     dir = (os.path.dirname(self.filename)
            if self.filename is not None else ".")
     formats = (["*.{0}".format(format.data().decode("ascii").lower())
                 for format in QImageReader.supportedImageFormats()])
     fname, tpye = QFileDialog.getOpenFileName(self,
                                               "Image Changer - Choose Image", dir,
                                               "Image files ({0})".format(" ".join(formats)))
     if fname:
         self.loadFile(True, fname)
Beispiel #10
0
    def test_qt(self):
        from PyQt5.QtGui import QImageReader, QFontDatabase
        from PyQt5.QtNetwork import QNetworkAccessManager
        from calibre.utils.img import image_from_data, image_to_data, test
        # Ensure that images can be read before QApplication is constructed.
        # Note that this requires QCoreApplication.libraryPaths() to return the
        # path to the Qt plugins which it always does in the frozen build,
        # because the QT_PLUGIN_PATH env var is set. On non-frozen builds,
        # it should just work because the hard-coded paths of the Qt
        # installation should work. If they do not, then it is a distro
        # problem.
        fmts = set(
            map(lambda x: x.data().decode('utf-8'),
                QImageReader.supportedImageFormats()))  # no2to3
        testf = {'jpg', 'png', 'svg', 'ico', 'gif'}
        self.assertEqual(
            testf.intersection(fmts), testf,
            "Qt doesn't seem to be able to load some of its image plugins. Available plugins: %s"
            % fmts)
        data = P('images/blank.png', allow_user_override=False, data=True)
        img = image_from_data(data)
        image_from_data(
            P('catalog/mastheadImage.gif',
              allow_user_override=False,
              data=True))
        for fmt in 'png bmp jpeg'.split():
            d = image_to_data(img, fmt=fmt)
            image_from_data(d)
        # Run the imaging tests
        test()

        from calibre.gui2 import Application
        os.environ.pop('DISPLAY', None)
        has_headless = isosx or islinux
        app = Application([], headless=has_headless)
        self.assertGreaterEqual(
            len(QFontDatabase().families()), 5,
            'The QPA headless plugin is not able to locate enough system fonts via fontconfig'
        )
        if has_headless:
            from calibre.ebooks.covers import create_cover
            create_cover('xxx', ['yyy'])
        na = QNetworkAccessManager()
        self.assertTrue(hasattr(na, 'sslErrors'),
                        'Qt not compiled with openssl')
        from PyQt5.QtWebKitWidgets import QWebView
        if iswindows:
            from PyQt5.Qt import QtWin
            QtWin
        QWebView()
        del QWebView
        del na
        del app
Beispiel #11
0
    def scanAllImages(folderPath):
        extensions = ['.%s' % fmt.data().decode("ascii").lower() for
                      fmt in QImageReader.supportedImageFormats()]
        images = []

        for root, dirs, files in os.walk(folderPath):
            for file in files:
                if file.lower().endswith(tuple(extensions)):
                    relativePath = os.path.join(root, file)
                    path = str(os.path.abspath(relativePath))
                    images.append(path)
        naturalSort(images, key=lambda x: x.lower())
        return images
 def _supported_file_formats() -> typing.List[str]:
     """
     Returns all supported file types. This is the intersection of readable and writable file formats.
     """
     supported_input_formats = set(
         f.data().decode("utf-8")
         for f in QImageReader.supportedImageFormats())
     supported_output_formats = set(
         f.data().decode("utf-8")
         for f in QImageWriter.supportedImageFormats())
     supported_formats = sorted(
         list(supported_input_formats.intersection(
             supported_output_formats)))
     return supported_formats
Beispiel #13
0
 def fileOpen(self):
     dir = os.path.dirname(
         self.filename) if self.filename is not None else "."
     # 构建所有QImageReader支持的图片类型列表
     formats = [
         '*.{0}'.format(format.data().decode("ascii").lower())
         for format in QImageReader.supportedImageFormats()
     ]
     # getOpenFileName返回
     fname, type = QFileDialog.getOpenFileName(
         self, "Image Changer - Choose Image", dir,
         "Image files (%s)" % " ".join(formats))
     # 如果选中了图片,加载图片
     if fname:
         self.loadFile(fname)
 def showPreviewDialog(self):
     """ Show images preview dialog """
     if self.previewDialog is None:
         #Create window if not exists
         self.previewDialog = DiviPluginPreviewDialog(self)
     model = self.tvIdentificationResult.model().sourceModel()
     item = model.findItem('attachments')
     image_items = []
     supportedFormats = QImageReader.supportedImageFormats()
     #Filter attachments by extension of supported formats
     for itm in item.childItems:
         ext = op.splitext(itm.name)[-1][1:].lower()
         if ext in supportedFormats:
             image_items.append( itm )
     fid = self.tvIdentificationResult.model().sourceModel().currentFeature
     self.previewDialog.show(fid, image_items)
Beispiel #15
0
 def openFile(self):
     if not self.leaving():
         return
     path = os.path.dirname(str(self.filename)) if self.filename else '.'
     formats = [
         '*.{}'.format(fmt.data().decode())
         for fmt in QImageReader.supportedImageFormats()
     ]
     filters = "Image & Label files (%s)" % ' '.join(formats + ['*.json'])
     filename, _ = QFileDialog.getOpenFileName(
         self, 'Choose Image or Label file', path, filters)
     if filename:
         if isinstance(filename, (tuple, list)):
             filename = filename[0]
         self.listWidget_files.clear()
         self.loadFile(str(filename))
Beispiel #16
0
 def openFile(self, _value=False):
     if not self.mayContinue():
         return
     path = os.path.dirname(str(self.filePath)) if self.filePath else '.'
     formats = ['*.%s' % fmt.data().decode("ascii").lower()
                for fmt in QImageReader.supportedImageFormats()]
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     filters = "Image files (%s)" % ' '.join(formats)
     # noinspection PyTypeChecker
     filename = QFileDialog.getOpenFileName(
         self, '%s - Choose Image file' % APP_NAME, path, filters,
         options=options)
     if filename:
         if isinstance(filename, (tuple, list)):
             filename = filename[0]
         self.loadFile(filename)
Beispiel #17
0
    def insertFromMimeData(self, mime):

        if mime.hasImage():
            tag = datetime.datetime.now().time().strftime("%H%M%S")
            url = QUrl("dropped_image_" + str(tag))
            self.dropImage(url, mime.imageData())
            mime.imageData().save("/tmp/" + url.toString(), "png") 
        elif mime.hasUrls():
            for url in mime.urls():
                info = QFileInfo(url.toLocalFile()) 
                ext = info.suffix().lower().encode('latin-1')
                if ext in QImageReader.supportedImageFormats():
                    print(str(info.filePath()))
                    self.dropImage(url, info.filePath())
                else:
                    self.dropTextFile(url)
        else:
            super().insertFromMimeData(mime)
Beispiel #18
0
    def __init__(self):
        QDialog.__init__(self)
        self.ui = Ui_DialogMain()

        self.ui.setupUi(self)

        self.ui.searchPB.clicked.connect(self.search_start)
        self.ui.nextPB.clicked.connect(self.next_item)
        self.ui.previousPB.clicked.connect(self.previous_item)

        self.path = "/media/zjay/Datas/workspace/pyqt_picture_browser/movies"
        self.filters = []
        self.name = ""
        for i in QImageReader.supportedImageFormats():
            self.filters.append("*." + str(i, encoding='utf-8'))

        self.iter = None
        self.to_start_item()
        self.show_item()
Beispiel #19
0
    def test_qt(self):
        from PyQt5.QtGui import QImageReader, QFontDatabase
        from PyQt5.QtNetwork import QNetworkAccessManager
        from calibre.utils.img import image_from_data, image_to_data, test
        # Ensure that images can be read before QApplication is constructed.
        # Note that this requires QCoreApplication.libraryPaths() to return the
        # path to the Qt plugins which it always does in the frozen build,
        # because the QT_PLUGIN_PATH env var is set. On non-frozen builds,
        # it should just work because the hard-coded paths of the Qt
        # installation should work. If they do not, then it is a distro
        # problem.
        fmts = set(map(lambda x: x.data().decode('utf-8'), QImageReader.supportedImageFormats()))  # no2to3
        testf = {'jpg', 'png', 'svg', 'ico', 'gif'}
        self.assertEqual(testf.intersection(fmts), testf, "Qt doesn't seem to be able to load some of its image plugins. Available plugins: %s" % fmts)
        data = P('images/blank.png', allow_user_override=False, data=True)
        img = image_from_data(data)
        image_from_data(P('catalog/mastheadImage.gif', allow_user_override=False, data=True))
        for fmt in 'png bmp jpeg'.split():
            d = image_to_data(img, fmt=fmt)
            image_from_data(d)
        # Run the imaging tests
        test()

        from calibre.gui2 import Application
        os.environ.pop('DISPLAY', None)
        has_headless = isosx or islinux
        app = Application([], headless=has_headless)
        self.assertGreaterEqual(len(QFontDatabase().families()), 5, 'The QPA headless plugin is not able to locate enough system fonts via fontconfig')
        if has_headless:
            from calibre.ebooks.covers import create_cover
            create_cover('xxx', ['yyy'])
        na = QNetworkAccessManager()
        self.assertTrue(hasattr(na, 'sslErrors'), 'Qt not compiled with openssl')
        from PyQt5.QtWebKitWidgets import QWebView
        if iswindows:
            from PyQt5.Qt import QtWin
            QtWin
        QWebView()
        del QWebView
        del na
        del app
 def supports(cls, file_format: str) -> bool:
     return file_format in QImageReader.supportedImageFormats()
Beispiel #21
0
    def __init__(self, mode, parent=None):
        """
        Constructor
        
        @param mode mode of the dialog
        @type int
        @param parent reference to the parent widget
        @type QWidget
        """
        super(ImageMarkupDialog, self).__init__(parent)
        self.setupUi(self)

        if mode == ImageMarkupDialog.MarkDownMode:
            self.sizeCheckBox.setEnabled(False)
            self.aspectRatioCheckBox.setEnabled(False)
            self.widthSpinBox.setEnabled(False)
            self.heightSpinBox.setEnabled(False)
        elif mode == ImageMarkupDialog.RestMode:
            self.titleEdit.setEnabled(False)

        self.__mode = mode
        self.__originalImageSize = QSize()

        filters = {
            'bmp': self.tr("Windows Bitmap File (*.bmp)"),
            'cur': self.tr("Windows Cursor File (*.cur)"),
            'dds': self.tr("DirectDraw-Surface File (*.dds)"),
            'gif': self.tr("Graphic Interchange Format File (*.gif)"),
            'icns': self.tr("Apple Icon File (*.icns)"),
            'ico': self.tr("Windows Icon File (*.ico)"),
            'jp2': self.tr("JPEG2000 File (*.jp2)"),
            'jpg': self.tr("JPEG File (*.jpg)"),
            'jpeg': self.tr("JPEG File (*.jpeg)"),
            'mng': self.tr("Multiple-Image Network Graphics File (*.mng)"),
            'pbm': self.tr("Portable Bitmap File (*.pbm)"),
            'pcx': self.tr("Paintbrush Bitmap File (*.pcx)"),
            'pgm': self.tr("Portable Graymap File (*.pgm)"),
            'png': self.tr("Portable Network Graphics File (*.png)"),
            'ppm': self.tr("Portable Pixmap File (*.ppm)"),
            'sgi': self.tr("Silicon Graphics Image File (*.sgi)"),
            'svg': self.tr("Scalable Vector Graphics File (*.svg)"),
            'svgz': self.tr("Compressed Scalable Vector Graphics File"
                            " (*.svgz)"),
            'tga': self.tr("Targa Graphic File (*.tga)"),
            'tif': self.tr("TIFF File (*.tif)"),
            'tiff': self.tr("TIFF File (*.tiff)"),
            'wbmp': self.tr("WAP Bitmap File (*.wbmp)"),
            'webp': self.tr("WebP Image File (*.webp)"),
            'xbm': self.tr("X11 Bitmap File (*.xbm)"),
            'xpm': self.tr("X11 Pixmap File (*.xpm)"),
        }

        inputFormats = []
        readFormats = QImageReader.supportedImageFormats()
        for readFormat in readFormats:
            try:
                inputFormats.append(filters[bytes(readFormat).decode()])
            except KeyError:
                pass
        inputFormats.sort()
        inputFormats.append(self.tr("All Files (*)"))
        if filters["png"] in inputFormats:
            inputFormats.remove(filters["png"])
            inputFormats.insert(0, filters["png"])
        self.imagePicker.setFilters(';;'.join(inputFormats))
        self.imagePicker.setMode(E5PathPickerModes.OpenFileMode)

        self.sizeCheckBox.setChecked(True)
        self.aspectRatioCheckBox.setChecked(True)

        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())

        self.__updateOkButton()
Beispiel #22
0
from PyQt5.QtGui import QImageReader

from Settings import SettingsKeys
from common import CommonUtils

__VERSION__ = "0.0.4"
__NAME__ = "ImagePlay"
__APP_NAME__ = str.format(f"{__NAME__} {__VERSION__}")

logger = CommonUtils.get_logger(__APP_NAME__)

settings = CommonUtils.AppSettings(
    __APP_NAME__,
    {
        SettingsKeys.image_delay: 3000,
        SettingsKeys.gif_delay: 1000,
        SettingsKeys.gif_by_frame: False,
        SettingsKeys.recurse_subdirs: False,
        SettingsKeys.shuffle: False,
        SettingsKeys.loop: True,
        SettingsKeys.image_scaled: True,
        SettingsKeys.dupe_image_view_zoom: 5
    }
)

supported_formats = []
for _format in QImageReader.supportedImageFormats():
    supported_formats.append(f".{str(_format, encoding='ascii').upper()}")
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

from PyQt5.QtGui import QImageReader

print(
    list(map(lambda x: x.data().decode(),
             QImageReader.supportedImageFormats())))
# ['bmp', 'cur', 'gif', 'icns', 'ico', 'jpeg', 'jpg', 'pbm', 'pgm', 'png', 'ppm', 'svg', 'svgz', 'tga', 'tif', 'tiff', 'wbmp', 'webp', 'xbm', 'xpm']
Beispiel #24
0
 def readableImageFormatsFilter():
     return toImageFileFilter(QImageReader.supportedImageFormats())
Beispiel #25
0
    def test_qt(self):
        from PyQt5.QtCore import QTimer
        from PyQt5.QtWidgets import QApplication
        from PyQt5.QtWebEngineWidgets import QWebEnginePage
        from PyQt5.QtGui import QImageReader, QFontDatabase
        from PyQt5.QtNetwork import QNetworkAccessManager
        from calibre.utils.img import image_from_data, image_to_data, test
        # Ensure that images can be read before QApplication is constructed.
        # Note that this requires QCoreApplication.libraryPaths() to return the
        # path to the Qt plugins which it always does in the frozen build,
        # because Qt is patched to know the layout of the calibre application
        # package. On non-frozen builds, it should just work because the
        # hard-coded paths of the Qt installation should work. If they do not,
        # then it is a distro problem.
        fmts = set(map(lambda x: x.data().decode('utf-8'), QImageReader.supportedImageFormats()))  # no2to3
        testf = {'jpg', 'png', 'svg', 'ico', 'gif'}
        self.assertEqual(testf.intersection(fmts), testf, "Qt doesn't seem to be able to load some of its image plugins. Available plugins: %s" % fmts)
        data = P('images/blank.png', allow_user_override=False, data=True)
        img = image_from_data(data)
        image_from_data(P('catalog/mastheadImage.gif', allow_user_override=False, data=True))
        for fmt in 'png bmp jpeg'.split():
            d = image_to_data(img, fmt=fmt)
            image_from_data(d)
        # Run the imaging tests
        test()

        from calibre.gui2 import ensure_app, destroy_app
        display_env_var = os.environ.pop('DISPLAY', None)
        try:
            ensure_app()
            self.assertGreaterEqual(len(QFontDatabase().families()), 5, 'The QPA headless plugin is not able to locate enough system fonts via fontconfig')
            from calibre.ebooks.covers import create_cover
            create_cover('xxx', ['yyy'])
            na = QNetworkAccessManager()
            self.assertTrue(hasattr(na, 'sslErrors'), 'Qt not compiled with openssl')
            if iswindows:
                from PyQt5.Qt import QtWin
                QtWin
            p = QWebEnginePage()

            def callback(result):
                callback.result = result
                if hasattr(print_callback, 'result'):
                    QApplication.instance().quit()

            def print_callback(result):
                print_callback.result = result
                if hasattr(callback, 'result'):
                    QApplication.instance().quit()

            p.runJavaScript('1 + 1', callback)
            p.printToPdf(print_callback)
            QTimer.singleShot(5000, lambda: QApplication.instance().quit())
            QApplication.instance().exec_()
            test_flaky = ismacos and not is_ci
            if not test_flaky:
                self.assertEqual(callback.result, 2, 'Simple JS computation failed')
                self.assertIn(b'Skia/PDF', bytes(print_callback.result), 'Print to PDF failed')
            del p
            del na
            destroy_app()
            del QWebEnginePage
        finally:
            if display_env_var is not None:
                os.environ['DISPLAY'] = display_env_var
Beispiel #26
0
    def init_images(self):
        self.images = []
        self.pt_names = set()
        self.seg_names = set()
        self.img_props = {}

        if self.work_dir is not None:
            # Get list of images
            extensions = [
                '.%s' % fmt.data().decode("ascii").lower()
                for fmt in QImageReader.supportedImageFormats()
            ]
            work_dir_file_names = [
                os.path.basename(file_name)
                for file_name in Path(self.work_dir).glob('*')
                if str(file_name).lower().endswith(tuple(extensions))
            ]

            if not self.no_anno_file:
                # Has annotation file
                with open(self.file_name, "r") as read_file:
                    data = json.load(read_file)
                # Init images list
                for entry in data:
                    if entry['file_name'] in work_dir_file_names:
                        image = Image(entry['file_name'],
                                      entry.get('points', None),
                                      entry.get('outlines', None),
                                      entry.get("outlines_cv", None),
                                      entry.get("property", None))
                        self.images.append(image)
                        # Update points names of all
                        for pt in entry['points']:
                            self.pt_names.add(pt['name'])

                        #Update seg name for all seg
                        for key, _ in entry['outlines_cv'].items():
                            self.seg_names.add(key)

                        #Update outline names
                        for key, item in entry['property'].items():

                            if type(item) is str:
                                # Categorical
                                if key in self.img_props:
                                    self.img_props[key].append(item)
                                else:
                                    self.img_props[key] = [item]
                            else:
                                # Numerical
                                if key not in self.img_props:
                                    self.img_props[key] = None

            else:
                # without annotation file
                for name in work_dir_file_names:
                    image = Image(name)
                    self.images.append(image)

            self.current_image_id = 0
            self.img_size = len(self.images)
            if self.img_size != 0:
                self.current_pixmap = QPixmap(
                    os.path.join(self.work_dir, self.get_current_image_name()))
                self.set_scale_fit_limit()

            self.filter_idx = list(range(0, self.img_size))
            self.sort_idx = list(range(0, self.img_size))
            self.flagged_img_idx = []