Beispiel #1
0
def get_dll(init=True, environ=None, isolated=False):
    """Find ImageMagick DLL and initialize it.

       Searches available paths with :func:`find_library`
       and then fallbacks to standard :func:`ctypes.util.find_liblrary`.
       Loads the DLL into memory, initializes it and warns if it has
       unsupported API and ABI versions.
    """
    if not hasattr(get_dll, '__dll') or isolated:
        logger.debug('Critical section - load MagickWand')
        with __lock:
            if not hasattr(get_dll, '__dll') or isolated:
                if not environ:
                    environ = os.environ

                path = find_library(name, abis, environ=environ)
                if not path:
                    msg = 'Could not find or load MagickWand'
                    raise PystaciaException(msg)

                msg = formattable('Loading MagickWand from {0}')
                logger.debug(msg.format(path))
                dll = CDLL(path)
                if not isolated:
                    get_dll.__dll = dll
                    get_dll.__dll.__inited = False
                else:
                    return dll

    dll = get_dll.__dll

    if init and not dll.__inited:
        init_dll(dll)

    return dll
Beispiel #2
0
def flip(image, axis):
    if axis.name == 'x':
        c_call(image, 'flip')
    elif axis.name == 'y':
        c_call(image, 'flop')
    else:
        raise PystaciaException('axis must be X or Y')
Beispiel #3
0
    def __init__(self, resource=None):
        """Construct new instance of resource."""
        self.__resource = resource if resource is not None else self._alloc()

        if self.__resource is None:
            tmpl = formattable('{0} _alloc method returned None')
            raise PystaciaException(tmpl.format(self.__class__.__name__))

        _track(self)
Beispiel #4
0
    def copy(self):
        """Get independent copy of this resource."""
        resource = self._clone()

        if resource is None:
            tmpl = formattable('{0} _clone method returned None')
            raise PystaciaException(tmpl.format(self.__class__.__name__))

        return self.__class__(resource)
Beispiel #5
0
def set_string(color, value):
    try:
        c_call(color, 'set_color', value)
    except PystaciaException:
        info = exc_info()
        matches = info[1].args[0].startswith
        if matches('unrecognized color') or matches('UnrecognizedColor'):
            raise PystaciaException('Unknown color string representation')

        reraise(*info)
Beispiel #6
0
    def resource(self):
        """Get underlying C resource.

           You can use this method to get access to raw C struct that you
           can use with :term:`ctypes` calls directly. It can be useful
           when you want to perform custom operations.
        """
        if self.__resource is None:
            tmpl = formattable('{0} already closed.')
            raise PystaciaException(tmpl.format(self.__class__.__name__))

        return self.__resource
Beispiel #7
0
def image_format(name):
    if isinstance(name, string_types):
        verb = name
        noun = ''
    elif hasattr(name, '__getitem__') and len(name) == 2:
        verb = name[0]
        noun = name[1]
    elif hasattr(name, '__getitem__') and len(name) == 3:
        return 'Magick' + name[0].title() + name[2].title()
    else:
        raise PystaciaException('Incorrect name format')

    return ('Magick' + ''.join(x.title() for x in verb.split('_')) + 'Image' +
            ''.join(x.title() for x in noun.split('_')))
Beispiel #8
0
def cast(value):
    if isinstance(value, Color):
        return value
    elif isinstance(value, integer_types):
        return from_int24(value)
    elif isinstance(value, string_types):
        return from_string(value)
    elif value.__len__:
        if len(value) == 3:
            return from_rgb(*value)
        elif len(value) == 4:
            return from_rgba(*value)

    template = formattable('Cannot cast {0} to Color instance.')
    raise PystaciaException(template.format(value))
Beispiel #9
0
    def _replace(self, resource):
        """Free current resource, claim resource from another object.

           Frees underlying resource, claims resource from another object
           and sets this object resource to claimed resource, effectively
           transferring resource property to this object.

           Not to be called directly
        """
        if isinstance(resource, Resource):
            resource = resource._claim()

        if resource is None:
            raise PystaciaException('Replacement resource cannot be None')

        self._free()
        self.__resource = resource
Beispiel #10
0
def rescale(image, width, height, factor, filter, blur):  # @ReservedAssignment
    if not filter:
        filter = filters.undefined  # @ReservedAssignment

    width, height = _proportionally(image, width, height)

    if not width and not height:
        if not factor:
            msg = 'Either width, height or factor must be provided'
            raise PystaciaException(msg)

        width, height = image.size
        if not hasattr(factor, '__getitem__'):
            factor = (factor, factor)
        width, height = width * factor[0], height * factor[1]

    c_call(image, 'resize', width, height, enum_lookup(filter, filters), blur)
Beispiel #11
0
def handle_result(result, restype, args, argtypes):
    if restype == c_char_p:
        result = native_str(result)
    if restype in (c_uint, c_ssize_t, c_size_t):
        result = int(result)
    elif restype == enum and not jython:
        result = result.value
    elif restype == MagickBoolean and not result:
        exc_type = ExceptionType()

        if argtypes[0] == MagickWand_p:
            klass = 'magick'
        elif argtypes[0] == PixelWand_p:
            klass = 'pixel'

        description = c_call(klass, 'get_exception', args[0], byref(exc_type))
        try:
            raise PystaciaException(native_str(string_at(description)))
        finally:
            c_call('magick_', 'relinquish_memory', description)

    return result
Beispiel #12
0
def lookup(mnemonic, enum=None, version=None, throw=True):
    if enum:
        mnemonic = enum.cast(mnemonic)

    if not version:
        version = get_version()

    value = None

    for entry in data.get(mnemonic.enum.name, []):
        if entry['_version'] > version:
            break
        value = entry.get(mnemonic.name)

    if value is None and throw:
        template = "Enumeration '{enum}' cannot map mnemonic '{mnemonic}'"
        template = formattable(template)
        enum = mnemonic.enum.name
        mnemonic = mnemonic.name
        raise PystaciaException(template.format(enum=enum, mnemonic=mnemonic))

    return value
Beispiel #13
0
    def __call__(self, arg):
        self.args.append(arg)

        if self.throw:
            raise PystaciaException('Error')