Exemple #1
0
def build_image(file,
                size,
                pre_key,
                crop=False,
                quality=90,
                cache=False,
                unique_key=None,
                constrain=False):
    """
    Builds a resized image based off of the original image.
    """
    try:
        quality = int(quality)
    except TypeError:
        quality = 90

    if settings.USE_S3_STORAGE:
        content = read_media_file_from_s3(file)
        image = Image.open(StringIO(content))
    else:
        if hasattr(file, 'path') and exists(file.path):
            image = Image.open(file.path)  # get image
        else:
            raise Http404

    image_options = {'quality': quality}
    if image.format == 'GIF':
        image_options['transparency'] = 0

    format = image.format
    if image.format in ('GIF', 'PNG'):
        if image.mode != "RGBA":
            image = image.convert("RGBA")
        image.format = format  # this is lost in conversion

    elif image.format == 'JPEG':
        # handle infamous error
        # IOError: cannot write mode P as JPEG
        if image.mode != "RGB":
            image = image.convert("RGB")

    if crop:
        image = image_rescale(image, size)  # thumbnail image
    else:
        format = image.format
        image = image.resize(size, Image.ANTIALIAS)  # resize image
        image.format = format

    binary = get_image_binary(image, **image_options)

    if cache:
        key = generate_image_cache_key(file, size, pre_key, crop, unique_key,
                                       quality, constrain)
        django_cache.add(key, binary,
                         60 * 60 * 24 * 30)  # cache for 30 days #issue/134

    return binary
Exemple #2
0
def build_image(file,
                size,
                pre_key,
                crop=False,
                quality=90,
                cache=False,
                unique_key=None):
    """
    Builds a resized image based off of the original image.
    """

    try:
        quality = int(quality)
    except:
        quality = 90

    if settings.USE_S3_STORAGE:
        content = read_media_file_from_s3(file)
        image = Image.open(StringIO(content))
    else:
        if hasattr(file, 'path') and exists(file.path):
            image = Image.open(file.path)  # get image
        else:
            raise Http404

    # handle infamous error
    # IOError: cannot write mode P as JPEG
    if image.mode != "RGB":
        image = image.convert("RGB")

    if crop:
        image = image_rescale(image, size)  # thumbnail image
    else:
        image = image.resize(size, Image.ANTIALIAS)  # resize image

    # mission: get binary
    output = StringIO()
    image.save(output, "JPEG", quality=quality)
    binary = output.getvalue()  # mission accomplished
    output.close()

    if cache:
        key = generate_image_cache_key(file, size, pre_key, crop, unique_key,
                                       quality)
        django_cache.add(key, binary,
                         60 * 60 * 24 * 30)  # cache for 30 days #issue/134

    return binary
Exemple #3
0
def build_image(file, size, pre_key, crop=False, quality=90, cache=False, unique_key=None, constrain=False):
    """
    Builds a resized image based off of the original image.
    """
    try:
        quality = int(quality)
    except TypeError:
        quality = 90

    if settings.USE_S3_STORAGE:
        content = read_media_file_from_s3(file)
        image = Image.open(StringIO(content))
    else:
        if hasattr(file, 'path') and exists(file.path):
            image = Image.open(file.path)  # get image
        else:
            raise Http404

    image_options = {'quality': quality}
    if image.format == 'GIF':
        image_options['transparency'] = 0

    format = image.format
    if image.format in ('GIF', 'PNG'):
        if image.mode != "RGBA":
            image = image.convert("RGBA")
        image.format = format  # this is lost in conversion

    elif image.format == 'JPEG':
        # handle infamous error
        # IOError: cannot write mode P as JPEG
        if image.mode != "RGB":
            image = image.convert("RGB")

    if crop:
        image = image_rescale(image, size)  # thumbnail image
    else:
        format = image.format
        image = image.resize(size, Image.ANTIALIAS)  # resize image
        image.format = format

    binary = get_image_binary(image, **image_options)

    if cache:
        key = generate_image_cache_key(file, size, pre_key, crop, unique_key, quality, constrain)
        django_cache.add(key, binary, 60 * 60 * 24 * 30)  # cache for 30 days #issue/134

    return binary
Exemple #4
0
def build_image(file, size, pre_key, crop=False, quality=90, cache=False, unique_key=None):
    """
    Builds a resized image based off of the original image.
    """

    try:
        quality = int(quality)
    except:
        quality = 90

    if settings.USE_S3_STORAGE:
        content = read_media_file_from_s3(file)
        image = Image.open(StringIO(content))
    else:
        if hasattr(file, 'path') and exists(file.path):
            image = Image.open(file.path)  # get image
        else:
            raise Http404

    # handle infamous error
    # IOError: cannot write mode P as JPEG
    if image.mode != "RGB":
        image = image.convert("RGB")

    if crop:
        image = image_rescale(image, size)  # thumbnail image
    else:
        image = image.resize(size, Image.ANTIALIAS)  # resize image

    # mission: get binary
    output = StringIO()
    image.save(output, "JPEG", quality=quality)
    binary = output.getvalue()  # mission accomplished
    output.close()

    if cache:
        key = generate_image_cache_key(file, size, pre_key, crop, unique_key, quality)
        django_cache.add(key, binary, 60 * 60 * 24 * 30)  # cache for 30 days #issue/134

    return binary
Exemple #5
0
def image_preview(request, app_label, model, id,  size):
    """
        Grab all image link within a peice of content
        and generate thumbnails of largest image
    """
    # get page object; protect size
    try:
        content_type = ContentType.objects.get(app_label=app_label, model=model)
        instance = content_type.get_object_for_this_type(id=id)
    except:
        return HttpResponseNotFound("Image not found.", mimetype="text/plain")
    
    keys = [settings.CACHE_PRE_KEY, IMAGE_PREVIEW_CACHE, model, str(instance.id), size]
    key = '.'.join(keys)
    response = cache.get(key)
    original_size = size
    
    if not response:
        from tendenci.core.base.utils import parse_image_sources, make_image_object_from_url, image_rescale

        # set sizes
        size_min = (30,30)
        size_cap = (512,512)
        
        size_tuple = size.split('x')
        if len(size_tuple) == 2: size = int(size_tuple[0]), int(size_tuple[1])
        else: size = int(size), int(size)

        if size > size_cap: size = size_cap

        image_urls = []

        image = Pil.new('RGBA',size_min)
    
        # find biggest image, dimension-wise
        for image_url in image_urls:
            image_candidate = make_image_object_from_url(image_url)
            if image_candidate:
                if image_candidate.size > image.size:
                    image = image_candidate

        if image.size[1] > size_min[1]:
        # rescale, convert-to true-colors; return response
    
            image = image_rescale(image, size)
            if image.mode != "RGB":
                image = image.convert("RGB")
    
            response = HttpResponse(mimetype='image/jpeg')
            
            image.save(response, "JPEG", quality=100)
            
            keys = [settings.CACHE_PRE_KEY, IMAGE_PREVIEW_CACHE, model, str(instance.id), size]
            key = '.'.join(keys)
            
            cache.set(key, response)
            return response
    
        else: # raise http 404 error (returns page not found)
            return HttpResponseNotFound("Image not found.", mimetype="text/plain")
    else:
        return response
Exemple #6
0
def image_preview(request, app_label, model, id, size):
    """
        Grab all image link within a peice of content
        and generate thumbnails of largest image
    """
    # get page object; protect size
    try:
        content_type = ContentType.objects.get(app_label=app_label,
                                               model=model)
        instance = content_type.get_object_for_this_type(id=id)
    except:
        return HttpResponseNotFound("Image not found.", mimetype="text/plain")

    keys = [
        settings.CACHE_PRE_KEY, IMAGE_PREVIEW_CACHE, model,
        str(instance.id), size
    ]
    key = '.'.join(keys)
    response = cache.get(key)
    original_size = size

    if not response:
        from tendenci.core.base.utils import parse_image_sources, make_image_object_from_url, image_rescale

        # set sizes
        size_min = (30, 30)
        size_cap = (512, 512)

        size_tuple = size.split('x')
        if len(size_tuple) == 2: size = int(size_tuple[0]), int(size_tuple[1])
        else: size = int(size), int(size)

        if size > size_cap: size = size_cap

        image_urls = []

        image = Pil.new('RGBA', size_min)

        # find biggest image, dimension-wise
        for image_url in image_urls:
            image_candidate = make_image_object_from_url(image_url)
            if image_candidate:
                if image_candidate.size > image.size:
                    image = image_candidate

        if image.size[1] > size_min[1]:
            # rescale, convert-to true-colors; return response

            image = image_rescale(image, size)
            if image.mode != "RGB":
                image = image.convert("RGB")

            response = HttpResponse(mimetype='image/jpeg')

            image.save(response, "JPEG", quality=100)

            keys = [
                settings.CACHE_PRE_KEY, IMAGE_PREVIEW_CACHE, model,
                str(instance.id), size
            ]
            key = '.'.join(keys)

            cache.set(key, response)
            return response

        else:  # raise http 404 error (returns page not found)
            return HttpResponseNotFound("Image not found.",
                                        mimetype="text/plain")
    else:
        return response