Пример #1
0
    def new_from_file(vips_filename, **kwargs):
        """Load an image from a file.

        This method can load images in any format supported by vips. The
        filename can include load options, for example::

            image = pyvips.Image.new_from_file('fred.jpg[shrink=2]')

        You can also supply options as keyword arguments, for example::

            image = pyvips.Image.new_from_file('fred.jpg', shrink=2)

        The full set of options available depend upon the load operation that
        will be executed. Try something like::

            $ vips jpegload

        at the command-line to see a summary of the available options for the
        JPEG loader.

        Loading is fast: only enough of the image is loaded to be able to fill
        out the header. Pixels will only be decompressed when they are needed.

        Args:
            vips_filename (str): The disc file to load the image from, with
                optional appended arguments.

        All loaders support at least the following options:

        Keyword args:
            memory (bool): If set True, load the image via memory rather than
                via a temporary disc file. See :meth:`.new_temp_file` for
                notes on where temporary files are created. Small images are
                loaded via memory by default, use ``VIPS_DISC_THRESHOLD`` to
                set the definition of small.
            access (Access): Hint the expected access pattern for the image.
            fail (bool): If set True, the loader will fail with an error on
                the first serious error in the file. By default, libvips
                will attempt to read everything it can from a damanged image.

        Returns:
            A new :class:`.Image`.

        Raises:
            :class:`.Error`

        """
        vips_filename = _to_bytes(vips_filename)
        filename = vips_lib.vips_filename_get_filename(vips_filename)
        options = vips_lib.vips_filename_get_options(vips_filename)
        name = vips_lib.vips_foreign_find_load(filename)
        if name == ffi.NULL:
            raise Error('unable to load from file {0}'.format(vips_filename))

        return pyvips.Operation.call(_to_string(ffi.string(name)),
                                     _to_string(ffi.string(filename)),
                                     string_options=_to_string(
                                         ffi.string(options)
                                     ), **kwargs)
Пример #2
0
    def write_to_file(self, vips_filename, **kwargs):
        """Write an image to a file on disc.

        This method can save images in any format supported by vips. The format
        is selected from the filename suffix. The filename can include embedded
        save options, see :func:`Image.new_from_file`.

        For example::

            image.write_to_file('fred.jpg[Q=95]')

        You can also supply options as keyword arguments, for example::

            image.write_to_file('fred.jpg', Q=95)

        The full set of options available depend upon the load operation that
        will be executed. Try something like::

            $ vips jpegsave

        at the command-line to see a summary of the available options for the
        JPEG saver.

        Args:
            vips_filename (str): The disc file to save the image to, with
                optional appended arguments.

        Other arguments depend upon the save operation.

        Returns:
            None

        Raises:
            :class:`.Error`

        """
        vips_filename = _to_bytes(vips_filename)
        filename = vips_lib.vips_filename_get_filename(vips_filename)
        options = vips_lib.vips_filename_get_options(vips_filename)
        name = vips_lib.vips_foreign_find_save(filename)
        if name == ffi.NULL:
            raise Error('unable to write to file {0}'.format(vips_filename))

        return pyvips.Operation.call(_to_string(ffi.string(name)),
                                     self,
                                     filename,
                                     string_options=_to_string(
                                         ffi.string(options)),
                                     **kwargs)
Пример #3
0
    def new_from_buffer(data, options, **kwargs):
        """Load a formatted image from memory.

        This behaves exactly as :meth:`new_from_file`, but the image is
        loaded from the memory object rather than from a file. The memory
        object can be anything that supports the Python buffer protocol.

        Args:
            data (array, bytearray, bytes, buffer): The memory object to
                load the image from.
            options (str): Load options as a string. Use ``""`` for no options.

        All loaders support at least the following options:

        Keyword args:
            access (Access): Hint the expected access pattern for the image.
            fail (bool): If set True, the loader will fail with an error on the
                first serious error in the image. By default, libvips will
                attempt to read everything it can from a damaged image.

        Returns:
            A new :class:`Image`.

        Raises:
            :class:`.Error`

        """
        pointer = vips_lib.vips_foreign_find_load_buffer(data, len(data))
        if pointer == ffi.NULL:
            raise Error('unable to load from buffer')
        name = _to_string(pointer)

        return pyvips.Operation.call(name, data,
                                     string_options=options, **kwargs)
Пример #4
0
    def new_from_source(source, options, **kwargs):
        """Load a formatted image from a source.

        This behaves exactly as :meth:`new_from_file`, but the image is
        loaded from the source rather than from a file.

        Args:
            source (Source): The source to load the image from.
            options (str): Load options as a string. Use ``""`` for no options.

        All loaders support at least the following options:

        Keyword args:
            access (Access): Hint the expected access pattern for the image.
            fail (bool): If set True, the loader will fail with an error on the
                first serious error in the image. By default, libvips will
                attempt to read everything it can from a damaged image.

        Returns:
            A new :class:`Image`.

        Raises:
            :class:`.Error`

        """
        pointer = vips_lib.vips_foreign_find_load_source(source.pointer)
        if pointer == ffi.NULL:
            raise Error('unable to load from source')
        name = _to_string(pointer)

        return pyvips.Operation.call(name,
                                     source,
                                     string_options=options,
                                     **kwargs)
Пример #5
0
    def write_to_buffer(self, format_string, **kwargs):
        """Write an image to memory.

        This method can save images in any format supported by vips. The format
        is selected from the suffix in the format string. This can include
        embedded save options, see :func:`Image.new_from_file`.

        For example::

            data = image.write_to_buffer('.jpg[Q=95]')

        You can also supply options as keyword arguments, for example::

            data = image.write_to_buffer('.jpg', Q=95)

        The full set of options available depend upon the load operation that
        will be executed. Try something like::

            $ vips jpegsave_buffer

        at the command-line to see a summary of the available options for the
        JPEG saver.

        Args:
            format_string (str): The suffix, plus any string-form arguments.

        Other arguments depend upon the save operation.

        Returns:
            A byte string.

        Raises:
            :class:`.Error`

        """
        format_string = _to_bytes(format_string)
        options = vips_lib.vips_filename_get_options(format_string)
        name = vips_lib.vips_foreign_find_save_buffer(format_string)
        if name == ffi.NULL:
            raise Error('unable to write to buffer')

        return pyvips.Operation.call(_to_string(ffi.string(name)),
                                     self,
                                     string_options=_to_string(
                                         ffi.string(options)),
                                     **kwargs)
Пример #6
0
    def from_enum(gtype, enum_value):
        """Turn an int back into an enum string.

        """

        pointer = vips_lib.vips_enum_nick(gtype, enum_value)
        if pointer == ffi.NULL:
            raise Error('value not in enum')

        return _to_string(pointer)
Пример #7
0
    def from_enum(gtype, enum_value):
        """Turn an int back into an enum string.

        """

        cstr = vips_lib.vips_enum_nick(gtype, enum_value)
        if cstr == 0:
            raise Error('value not in enum')

        return _to_string(ffi.string(cstr))
Пример #8
0
    def nick(self):
        """Make a human-readable name for a connection suitable for error
        messages.

        """

        so = ffi.cast('VipsConnection *', self.pointer)
        pointer = vips_lib.vips_connection_nick(so)
        if pointer == ffi.NULL:
            return None
        else:
            return _to_string(pointer)
Пример #9
0
    def filename(self):
        """Get the filename associated with a connection. Return None if there
        is no associated file.

        """

        so = ffi.cast('VipsConnection *', self.pointer)
        pointer = vips_lib.vips_connection_filename(so)
        if pointer == ffi.NULL:
            return None
        else:
            return _to_string(pointer)
Пример #10
0
        def add_construct(self, pspec, argument_class, argument_instance, a,
                          b):
            flags = argument_class.flags
            if (flags & _CONSTRUCT) != 0:
                name = _to_string(ffi.string(pspec.name))

                # libvips uses '-' to separate parts of arg names, but we
                # need '_' for Python
                name = name.replace('-', '_')

                args.append([name, flags])

            return ffi.NULL
Пример #11
0
    def write_to_target(self, target, format_string, **kwargs):
        """Write an image to a target.

        This method will write the image to the target in the format
        specified in the suffix in the format string. This can include
        embedded save options, see :func:`Image.write_to_file`.

        For example::

            image.write_to_target(target, '.jpg[Q=95]')

        You can also supply options as keyword arguments, for example::

            image.write_to_target(target, '.jpg', Q=95)

        The full set of options available depend upon the save operation that
        will be executed. Try something like::

            $ vips jpegsave_target

        at the command-line to see a summary of the available options for the
        JPEG saver.

        Args:
            target (Target): The target to write the image to
            format_string (str): The suffix, plus any string-form arguments.

        Other arguments depend upon the save operation.

        Returns:
            None

        Raises:
            :class:`.Error`

        """
        format_string = _to_bytes(format_string)

        pointer = vips_lib.vips_filename_get_options(format_string)
        options = _to_string_copy(pointer)

        pointer = vips_lib.vips_foreign_find_save_target(format_string)
        if pointer == ffi.NULL:
            raise Error('unable to write to target')
        name = _to_string(pointer)

        return pyvips.Operation.call(name,
                                     self,
                                     target,
                                     string_options=options,
                                     **kwargs)
Пример #12
0
def values_for_enum(gtype):
    """Get all values for a enum (gtype)."""

    g_type_class = gobject_lib.g_type_class_ref(gtype)
    g_enum_class = ffi.cast('GEnumClass *', g_type_class)

    values = []

    # -1 since we always have a "last" member.
    for i in range(0, g_enum_class.n_values - 1):
        value = _to_string(g_enum_class.values[i].value_nick)
        values.append(value)

    return values
Пример #13
0
    def get_args(self):
        args = []

        if at_least_libvips(8, 7):
            p_names = ffi.new('char**[1]')
            p_flags = ffi.new('int*[1]')
            p_n_args = ffi.new('int[1]')

            result = vips_lib.vips_object_get_args(self.object, p_names,
                                                   p_flags, p_n_args)

            if result != 0:
                raise Error('unable to get arguments from operation')

            p_names = p_names[0]
            p_flags = p_flags[0]
            n_args = p_n_args[0]

            for i in range(0, n_args):
                flags = p_flags[i]
                if (flags & _CONSTRUCT) != 0:
                    name = _to_string(p_names[i])

                    # libvips uses '-' to separate parts of arg names, but we
                    # need '_' for Python
                    name = name.replace('-', '_')

                    args.append([name, flags])
        else:

            def add_construct(self, pspec, argument_class, argument_instance,
                              a, b):
                flags = argument_class.flags
                if (flags & _CONSTRUCT) != 0:
                    name = _to_string(pspec.name)

                    # libvips uses '-' to separate parts of arg names, but we
                    # need '_' for Python
                    name = name.replace('-', '_')

                    args.append([name, flags])

                return ffi.NULL

            cb = ffi.callback('VipsArgumentMapFn', add_construct)
            vips_lib.vips_argument_map(self.object, cb, ffi.NULL, ffi.NULL)

        return args
Пример #14
0
    def get_fields(self):
        """Get a list of all the metadata fields on an image.

        Returns:
            [string]

        """

        array = vips_lib.vips_image_get_fields(self.pointer)
        names = []
        i = 0
        while array[i] != ffi.NULL:
            name = _to_string(ffi.string(array[i]))
            names.append(name)
            glib_lib.g_free(array[i])
            i += 1
        glib_lib.g_free(array)

        return names
Пример #15
0
def get_suffixes():
    """Get a list of all the filename suffixes supported by libvips.

    Returns:
        [string]

    """

    names = []

    if at_least_libvips(8, 8):
        array = vips_lib.vips_foreign_get_suffixes()
        i = 0
        while array[i] != ffi.NULL:
            name = _to_string(array[i])
            if name not in names:
                names.append(name)
            glib_lib.g_free(array[i])
            i += 1
        glib_lib.g_free(array)

    return names
Пример #16
0
def path_mode7(filename):
    return _to_string(ffi.string(vips_lib.vips_path_mode7(
        _to_bytes(filename))))
Пример #17
0
    def get_description(self):
        """Get the description of a GObject."""

        vo = ffi.cast('VipsObject *', self.pointer)
        return _to_string(ffi.string(vips_lib.vips_object_get_description(vo)))
Пример #18
0
 def add_construct(self, pspec, argument_class, argument_instance,
                   a, b):
     add_args(_to_string(pspec.name), argument_class.flags)
     return ffi.NULL
Пример #19
0
    def __init__(self, operation_name):
        op = Operation.new_from_name(operation_name)

        self.description = op.get_description()
        self.flags = vips_lib.vips_operation_get_flags(op.pointer)

        # build a list of constructor arg [name, flags] pairs in arg order
        arguments = []

        def add_args(name, flags):
            if (flags & _CONSTRUCT) != 0:
                # libvips uses '-' to separate parts of arg names, but we
                # need '_' for Python
                name = name.replace('-', '_')
                arguments.append([name, flags])

        if at_least_libvips(8, 7):
            p_names = ffi.new('char**[1]')
            p_flags = ffi.new('int*[1]')
            p_n_args = ffi.new('int[1]')
            result = vips_lib.vips_object_get_args(op.vobject, p_names,
                                                   p_flags, p_n_args)
            if result != 0:
                raise Error('unable to get arguments from operation')
            p_names = p_names[0]
            p_flags = p_flags[0]
            n_args = p_n_args[0]

            for i in range(0, n_args):
                add_args(_to_string(p_names[i]), p_flags[i])
        else:

            def add_construct(self, pspec, argument_class, argument_instance,
                              a, b):
                add_args(_to_string(pspec.name), argument_class.flags)
                return ffi.NULL

            cb = ffi.callback('VipsArgumentMapFn', add_construct)
            vips_lib.vips_argument_map(op.vobject, cb, ffi.NULL, ffi.NULL)

        # logger.debug('arguments = %s', self.arguments)

        # build a hash from arg name to detailed arg information
        self.details = {}
        for name, flags in arguments:
            self.details[name] = {
                "name": name,
                "flags": flags,
                "blurb": op.get_blurb(name),
                "type": op.get_typeof(name)
            }

        # lists of arg names by category
        self.required_input = []
        self.optional_input = []
        self.required_output = []
        self.optional_output = []

        for name, flags in arguments:
            if ((flags & _INPUT) != 0 and (flags & _REQUIRED) != 0
                    and (flags & _DEPRECATED) == 0):
                self.required_input.append(name)

                # required inputs which we MODIFY are also required outputs
                if (flags & _MODIFY) != 0:
                    self.required_output.append(name)

            if ((flags & _OUTPUT) != 0 and (flags & _REQUIRED) != 0
                    and (flags & _DEPRECATED) == 0):
                self.required_output.append(name)

            # we let deprecated optional args through, but warn about them
            # if they get used, see below
            if ((flags & _INPUT) != 0 and (flags & _REQUIRED) == 0):
                self.optional_input.append(name)

            if ((flags & _OUTPUT) != 0 and (flags & _REQUIRED) == 0):
                self.optional_output.append(name)

        # find the first required input image arg, if any ... that will be self
        self.member_x = None
        for name in self.required_input:
            details = self.details[name]
            if details['type'] == GValue.image_type:
                self.member_x = name
                break

        # method args are required args, but without the image they are a
        # method on
        if self.member_x is not None:
            self.method_args = list(self.required_input)
            self.method_args.remove(self.member_x)
        else:
            self.method_args = self.required_input
Пример #20
0
    def get(self):
        """Get the contents of a GValue.

        The contents of the GValue are read out as a Python type.
        """

        # logger.debug('GValue.get: self = %s', self)

        gtype = self.gvalue.g_type
        fundamental = gobject_lib.g_type_fundamental(gtype)

        result = None

        if gtype == GValue.gbool_type:
            result = bool(gobject_lib.g_value_get_boolean(self.gvalue))
        elif gtype == GValue.gint_type:
            result = gobject_lib.g_value_get_int(self.gvalue)
        elif gtype == GValue.gdouble_type:
            result = gobject_lib.g_value_get_double(self.gvalue)
        elif fundamental == GValue.genum_type:
            return GValue.from_enum(gtype,
                                    gobject_lib.g_value_get_enum(self.gvalue))
        elif fundamental == GValue.gflags_type:
            result = gobject_lib.g_value_get_flags(self.gvalue)
        elif gtype == GValue.gstr_type:
            pointer = gobject_lib.g_value_get_string(self.gvalue)

            if pointer != ffi.NULL:
                result = _to_string(pointer)
        elif gtype == GValue.refstr_type:
            psize = ffi.new('size_t *')
            pointer = vips_lib.vips_value_get_ref_string(self.gvalue, psize)

            # psize[0] will be number of bytes in string, but just assume it's
            # NULL-terminated
            result = _to_string(pointer)
        elif gtype == GValue.image_type:
            # g_value_get_object() will not add a ref ... that is
            # held by the gvalue
            go = gobject_lib.g_value_get_object(self.gvalue)
            vi = ffi.cast('VipsImage *', go)

            # we want a ref that will last with the life of the vimage:
            # this ref is matched by the unref that's attached to finalize
            # by Image()
            gobject_lib.g_object_ref(go)

            result = pyvips.Image(vi)
        elif gtype == GValue.array_int_type:
            pint = ffi.new('int *')
            array = vips_lib.vips_value_get_array_int(self.gvalue, pint)

            result = []
            for i in range(0, pint[0]):
                result.append(array[i])
        elif gtype == GValue.array_double_type:
            pint = ffi.new('int *')
            array = vips_lib.vips_value_get_array_double(self.gvalue, pint)

            result = []
            for i in range(0, pint[0]):
                result.append(array[i])
        elif gtype == GValue.array_image_type:
            pint = ffi.new('int *')
            array = vips_lib.vips_value_get_array_image(self.gvalue, pint)

            result = []
            for i in range(0, pint[0]):
                vi = array[i]
                gobject_lib.g_object_ref(vi)
                image = pyvips.Image(vi)
                result.append(image)
        elif gtype == GValue.blob_type:
            psize = ffi.new('size_t *')
            array = vips_lib.vips_value_get_blob(self.gvalue, psize)
            buf = ffi.cast('char*', array)

            result = ffi.unpack(buf, psize[0])
        else:
            raise Error('unsupported gtype for get {0}'.format(
                type_name(gtype)))

        return result
Пример #21
0
def nickname_find(gtype):
    """Return the nickname for a GType."""

    return _to_string(ffi.string(vips_lib.vips_nickname_find(gtype)))
Пример #22
0
def type_name(gtype):
    """Return the name for a GType."""

    return _to_string(ffi.string(gobject_lib.g_type_name(gtype)))
Пример #23
0
    def get_description(self):
        """Get the description of a GObject."""

        return _to_string(vips_lib.vips_object_get_description(self.vobject))
Пример #24
0
    def get_blurb(self, name):
        """Get the blurb for a GObject property."""

        c_str = gobject_lib.g_param_spec_get_blurb(self._get_pspec(name))
        return _to_string(c_str)