示例#1
0
 def process(self, img):
     # Convert bgcolor string to RGB value.
     background_color = ImageColor.getrgb(self.background_color)
     # Handle palleted images.
     img = img.convert('RGBA')
     # Copy orignial image and flip the orientation.
     reflection = img.copy().transpose(Image.FLIP_TOP_BOTTOM)
     # Create a new image filled with the bgcolor the same size.
     background = Image.new("RGBA", img.size, background_color)
     # Calculate our alpha mask.
     start = int(255 - (255 * self.opacity))  # The start of our gradient.
     steps = int(255 * self.size)  # The number of intermedite values.
     increment = (255 - start) / float(steps)
     mask = Image.new('L', (1, 255))
     for y in range(255):
         if y < steps:
             val = int(y * increment + start)
         else:
             val = 255
         mask.putpixel((0, y), val)
     alpha_mask = mask.resize(img.size)
     # Merge the reflection onto our background color using the alpha mask.
     reflection = Image.composite(background, reflection, alpha_mask)
     # Crop the reflection.
     reflection_height = int(img.size[1] * self.size)
     reflection = reflection.crop((0, 0, img.size[0], reflection_height))
     # Create new image sized to hold both the original image and
     # the reflection.
     composite = Image.new("RGBA", (img.size[0], img.size[1] + reflection_height), background_color)
     # Paste the orignal image and the reflection into the composite image.
     composite.paste(img, (0, 0))
     composite.paste(reflection, (0, img.size[1]))
     # Return the image complete with reflection effect.
     return composite
示例#2
0
 def process(self, img):
     original = img = img.convert('RGB')
     overlay = Image.new('RGB', original.size, self.color)
     mask = Image.new('RGBA', original.size,
                      (0, 0, 0, int((1.0 - self.overlay_opacity) * 255)))
     img = Image.composite(original, overlay, mask).convert('RGB')
     return img
示例#3
0
def test_format_normalization():
    """
    Make sure formats are normalized by ``prepare_image()``.
    See https://github.com/matthewwithanm/django-imagekit/issues/262
    """
    im = Image.new('RGBA', (100, 100))
    ok_('transparency' in prepare_image(im, 'gIF')[1])
示例#4
0
def test_format_normalization():
    """
    Make sure formats are normalized by ``prepare_image()``.
    See https://github.com/matthewwithanm/django-imagekit/issues/262
    """
    im = Image.new('RGBA', (100, 100))
    ok_('transparency' in prepare_image(im, 'gIF')[1])
示例#5
0
def test_resize_antialiasing():
    """
    Test that the Resize processor antialiases.

    The Resize processor is used by all of the Resize* variants, so this should
    cover all of resize processors. Basically, this is to test that it converts
    to RGBA mode before resizing.

    Related: jdriscoll/django-imagekit#192

    """
    # Create a palette image and draw a circle into it.
    img = Image.new('P', (500, 500), 1)
    img.putpalette([
        0,   0,   0,
        255, 255, 255,
        0,   0,   255,
    ])
    d = ImageDraw.ImageDraw(img)
    d.ellipse((100, 100, 400, 400), fill=2)

    # Resize the image using the Resize processor
    img = Resize(100, 100).process(img)

    # Count the number of colors
    color_count = len(list(filter(None, img.histogram())))

    assert_true(color_count > 2)
示例#6
0
def test_resize_antialiasing():
    """
    Test that the Resize processor antialiases.

    The Resize processor is used by all of the Resize* variants, so this should
    cover all of resize processors. Basically, this is to test that it converts
    to RGBA mode before resizing.

    Related: jdriscoll/django-imagekit#192

    """
    # Create a palette image and draw a circle into it.
    img = Image.new('P', (500, 500), 1)
    img.putpalette([
        0,
        0,
        0,
        255,
        255,
        255,
        0,
        0,
        255,
    ])
    d = ImageDraw.ImageDraw(img)
    d.ellipse((100, 100, 400, 400), fill=2)

    # Resize the image using the Resize processor
    img = Resize(100, 100).process(img)

    # Count the number of colors
    color_count = len(list(filter(None, img.histogram())))

    assert_true(color_count > 2)
示例#7
0
def test_convert():
    img = Image.new('RGBA', (200, 100))

    img_RGBa = Convert("RGBa").process(img)
    eq_(img_RGBa.mode, "RGBa")

    img_RGBa_RGBA = Convert("RGBA").process(img)
    eq_(img_RGBa_RGBA.mode, "RGBA")
示例#8
0
def test_coloroverlay():
    """
    Test that the ColorOverlay processor
    """
    img = Image.new('RGB', (200, 100))
    color = ImageColor.getrgb('#cc0000')
    img = ColorOverlay(color, overlay_opacity=1.0).process(img)
    eq_(img.getpixel((0, 0)), (204, 0, 0))
示例#9
0
def test_resize_rounding():
    """
    Regression test for matthewwithanm/pilkit#1
    """

    img = Image.new('RGB', (95, 95))
    img = ResizeToFill(28, 28).process(img)
    eq_(img.size, (28, 28))
示例#10
0
def test_resize_rounding():
    """
    Regression test for matthewwithanm/pilkit#1
    """

    img = Image.new('RGB', (95, 95))
    img = ResizeToFill(28, 28).process(img)
    eq_(img.size, (28, 28))
示例#11
0
def test_coloroverlay():
    """
    Test that the ColorOverlay processor
    """
    img = Image.new('RGB', (200, 100))
    color = ImageColor.getrgb('#cc0000')
    img = ColorOverlay(color, overlay_opacity=1.0).process(img)
    eq_(img.getpixel((0,0)), (204, 0, 0))
示例#12
0
def test_convert():
    img = Image.new('RGBA', (200, 100))

    img_RGBa = Convert("RGBa").process(img)
    eq_(img_RGBa.mode, "RGBa")

    img_RGBa_RGBA = Convert("RGBA").process(img)
    eq_(img_RGBa_RGBA.mode, "RGBA")
示例#13
0
def test_resizetofit():
    # First create an image with aspect ratio 2:1...
    img = Image.new('RGB', (200, 100))

    # ...then resize it to fit within a 100x100 canvas.
    img = ResizeToFit(100, 100).process(img)

    # Assert that the image has maintained the aspect ratio.
    eq_(img.size, (100, 50))
示例#14
0
def test_resizetofit():
    # First create an image with aspect ratio 2:1...
    img = Image.new('RGB', (200, 100))

    # ...then resize it to fit within a 100x100 canvas.
    img = ResizeToFit(100, 100).process(img)

    # Assert that the image has maintained the aspect ratio.
    eq_(img.size, (100, 50))
示例#15
0
def test_upscale():
    """
    Test that the upscale argument works as expected.

    """

    img = Image.new('RGB', (100, 100))

    for P in [Resize, ResizeToFit, ResizeToFill, SmartResize]:
        img2 = P(500, 500, upscale=True).process(img)
        eq_(img2.size, (500, 500))

        img2 = P(500, 500, upscale=False).process(img)
        eq_(img2.size, (100, 100))
示例#16
0
def test_upscale():
    """
    Test that the upscale argument works as expected.

    """

    img = Image.new('RGB', (100, 100))

    for P in [Resize, ResizeToFit, ResizeToFill, SmartResize]:
        img2 = P(500, 500, upscale=True).process(img)
        eq_(img2.size, (500, 500))

        img2 = P(500, 500, upscale=False).process(img)
        eq_(img2.size, (100, 100))
示例#17
0
文件: base.py 项目: Ak1mbo0/Bethania
 def process(self, img):
     # Convert bgcolor string to RGB value.
     background_color = ImageColor.getrgb(self.background_color)
     # Handle palleted images.
     img = img.convert('RGBA')
     # Copy orignial image and flip the orientation.
     reflection = img.copy().transpose(Image.FLIP_TOP_BOTTOM)
     # Create a new image filled with the bgcolor the same size.
     background = Image.new("RGBA", img.size, background_color)
     # Calculate our alpha mask.
     start = int(255 - (255 * self.opacity))  # The start of our gradient.
     steps = int(255 * self.size)  # The number of intermedite values.
     increment = (255 - start) / float(steps)
     mask = Image.new('L', (1, 255))
     for y in range(255):
         if y < steps:
             val = int(y * increment + start)
         else:
             val = 255
         mask.putpixel((0, y), val)
     alpha_mask = mask.resize(img.size)
     # Merge the reflection onto our background color using the alpha mask.
     reflection = Image.composite(background, reflection, alpha_mask)
     # Crop the reflection.
     reflection_height = int(img.size[1] * self.size)
     reflection = reflection.crop((0, 0, img.size[0], reflection_height))
     # Create new image sized to hold both the original image and
     # the reflection.
     composite = Image.new("RGBA",
                           (img.size[0], img.size[1] + reflection_height),
                           background_color)
     # Paste the orignal image and the reflection into the composite image.
     composite.paste(img, (0, 0))
     composite.paste(reflection, (0, img.size[1]))
     # Return the image complete with reflection effect.
     return composite
示例#18
0
 def process(self, img):
     original = img = img.convert('RGBA')
     for name in ['Color', 'Brightness', 'Contrast', 'Sharpness']:
         factor = getattr(self, name.lower())
         if factor != 1.0:
             try:
                 img = getattr(ImageEnhance, name)(img).enhance(factor)
             except ValueError:
                 pass
             else:
                 # PIL's Color and Contrast filters both convert the image
                 # to L mode, losing transparency info, so we put it back.
                 # See https://github.com/jdriscoll/django-imagekit/issues/64
                 if name in ('Color', 'Contrast'):
                     img = Image.merge('RGBA', img.split()[:3] +
                             original.split()[3:4])
     return img
示例#19
0
文件: base.py 项目: Ak1mbo0/Bethania
 def process(self, img):
     original = img = img.convert('RGBA')
     for name in ['Color', 'Brightness', 'Contrast', 'Sharpness']:
         factor = getattr(self, name.lower())
         if factor != 1.0:
             try:
                 img = getattr(ImageEnhance, name)(img).enhance(factor)
             except ValueError:
                 pass
             else:
                 # PIL's Color and Contrast filters both convert the image
                 # to L mode, losing transparency info, so we put it back.
                 # See https://github.com/jdriscoll/django-imagekit/issues/64
                 if name in ('Color', 'Contrast'):
                     img = Image.merge(
                         'RGBA',
                         img.split()[:3] + original.split()[3:4])
     return img
def process(image_url,  processor = None, width=None, height=None, resolution=None, quality=100):
    conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
    bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) 
    if image_url[0] =='/': image_url = image_url[1:] 
    r = requests.get(image_url.replace('https', 'http'))
    img = Image.open(StringIO(r.content))
    processor = ResizeToFit(width, height)
    new_img = processor.process(img)
    new_file = StringIO()
    save_image(new_img, new_file, 'JPEG')
    new_k = Key(bucket)
    parts = urlparse(image_url)
    img_name = os.path.splitext(os.path.basename(parts.path))[0]
    new_k.key = 'il/{}x{}/{}.jpeg'.format(width, height, img_name)
    new_k.content_type = 'image/jpeg'
    new_k.set_contents_from_file(new_file, policy='public-read')
    new_image_url = new_k.generate_url(0, query_auth=False, force_http=True)
    processed_image,_ = ProcessedImage.objects.update_or_create(source_image = image_url, processed_image = new_image_url)
    return processed_image
    
    
示例#21
0
文件: base.py 项目: Ak1mbo0/Bethania
 def process(self, img):
     img = img.convert('RGBA')
     new_img = Image.new('RGBA', img.size, self.background_color)
     new_img.paste(img, img)
     return new_img
示例#22
0
def test_should_raise_exception_when_crop_is_passed_without_height_and_width():
    img = Image.new('RGB', (100, 100))
    try:
        Thumbnail(crop=True).process(img)
    except Exception as e:
        eq_(str(e), 'You must provide both a width and height when cropping.')
示例#23
0
def test_should_repass_upscale_option_false(my_mock):
    img = Image.new('RGB', (100, 100))
    Thumbnail(height=200, width=200, upscale=False).process(img)
    my_mock.assert_called_once_with(width=200, upscale=False, height=200)
示例#24
0
def test_should_call_resizetofill_when_crop_and_ancho_is_passed(my_mock):
    img = Image.new('RGB', (100, 100))
    Thumbnail(height=200, width=200, anchor='fake').process(img)
    assert_true(my_mock.called)
示例#25
0
def test_resizetofit_mat():
    img = Image.new('RGB', (200, 100))
    img = ResizeToFit(100, 100, mat_color=0x000000).process(img)
    eq_(img.size, (100, 100))
示例#26
0
def test_resizetofit_mat():
    img = Image.new('RGB', (200, 100))
    img = ResizeToFit(100, 100, mat_color=0x000000).process(img)
    eq_(img.size, (100, 100))
示例#27
0
def test_make_gifs_opaque():
    dir = os.path.dirname(__file__)
    path = os.path.join(dir, 'assets', 'cat.gif')
    gif = Image.open(path)
    MakeOpaque().process(gif)
示例#28
0
def test_make_gifs_opaque():
    dir = os.path.dirname(__file__)
    path = os.path.join(dir, 'assets', 'cat.gif')
    gif = Image.open(path)
    MakeOpaque().process(gif)
示例#29
0
def test_should_call_resizetofit_when_crop_is_not_passed(my_mock):
    img = Image.new('RGB', (100, 100))
    Thumbnail(height=200, width=200, crop=False).process(img)
    assert_true(my_mock.called)
示例#30
0
def test_should_call_resizetofill_when_crop_and_ancho_is_passed(my_mock):
    img = Image.new('RGB', (100, 100))
    Thumbnail(height=200, width=200, anchor='fake').process(img)
    assert_true(my_mock.called)
示例#31
0
def test_should_repass_upscale_option_false(my_mock):
    img = Image.new('RGB', (100, 100))
    Thumbnail(height=200, width=200, upscale=False).process(img)
    my_mock.assert_called_once_with(width=200, upscale=False, height=200)
示例#32
0
def test_should_raise_exception_when_crop_is_passed_without_height_and_width():
    img = Image.new('RGB', (100, 100))
    try:
        Thumbnail(crop=True).process(img)
    except Exception as e:
        eq_(str(e), 'You must provide both a width and height when cropping.')
示例#33
0
 def process(self, img):
     original = img = img.convert('RGB')
     overlay = Image.new('RGB', original.size, self.color)
     mask = Image.new('RGBA', original.size, (0,0,0,int((1.0 - self.overlay_opacity)*255)))
     img = Image.composite(original, overlay, mask).convert('RGB')
     return img
示例#34
0
def test_should_call_resizetofit_when_crop_is_not_passed(my_mock):
    img = Image.new('RGB', (100, 100))
    Thumbnail(height=200, width=200, crop=False).process(img)
    assert_true(my_mock.called)
示例#35
0
def test_GaussianBlur_radius_7():
    img = GaussianBlur(radius=7).process(create_image())
    img = img.crop((112, 112, 144, 144))

    expected_img = Image.open(get_image_file("GaussianBlur_radius_7.png"))
    assert_true(compare_images(img, expected_img))
示例#36
0
 def process(self, img):
     img = img.convert('RGBA')
     new_img = Image.new('RGBA', img.size, self.background_color)
     new_img.paste(img, img)
     return new_img
示例#37
0
def create_image():
    return Image.open(get_image_file())
 def process(self, img):
     original = img.convert('RGBA')
     overlay = Image.open(self.watermark_image)
     img = Image.alpha_composite(original, overlay).convert('RGB')
     return img