Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill Color of PIL Cropping/Thumbnailing

I am taking an image file and thumbnailing and cropping it with the following PIL code:

        image = Image.open(filename)
        image.thumbnail(size, Image.ANTIALIAS)
        image_size = image.size
        thumb = image.crop( (0, 0, size[0], size[1]) )
        offset_x = max( (size[0] - image_size[0]) / 2, 0 )
        offset_y = max( (size[1] - image_size[1]) / 2, 0 )
        thumb = ImageChops.offset(thumb, offset_x, offset_y)                
        thumb.convert('RGBA').save(filename, 'JPEG')

This works great, except when the image isn't the same aspect ratio, the difference is filled in with a black color (or maybe an alpha channel?). I'm ok with the filling, I'd just like to be able to select the fill color -- or better yet an alpha channel.

Output example:

output

How can I specify the fill color?

like image 850
Erik Avatar asked Jul 26 '12 06:07

Erik


People also ask

How do I crop an image in PIL?

crop() method is used to crop a rectangular portion of any image. Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate. Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple).

What is PIL image format?

Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux. The latest version of PIL is 1.1.

What is image Fromarray?

The Image. fromarray() function takes the array object as the input and returns the image object made from the array object.29-Dec-2020.


1 Answers

Its a bit easier to paste your re-sized thumbnail image onto a new image, that is the colour (and alpha value) you want.

You can create an image, and speicfy its colour in a RGBA tuple like this:

Image.new('RGBA', size, (255,0,0,255))

Here there is there is no transparency as the alpha band is set to 255. But the background will be red. Using this image to paste onto we can create thumbnails with any colour like this:

enter image description here

If we set the alpha band to 0, we can paste onto a transparent image, and get this:

enter image description here

Example code:

import Image

image = Image.open('1_tree_small.jpg')
size=(50,50)
image.thumbnail(size, Image.ANTIALIAS)
# new = Image.new('RGBA', size, (255, 0, 0, 255))  #without alpha, red
new = Image.new('RGBA', size, (255, 255, 255, 0))  #with alpha
new.paste(image,((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
new.save('saved4.png')
like image 171
fraxel Avatar answered Sep 27 '22 21:09

fraxel