How to add border to an image using pillow in python
The PIL library
PIL or Python imaging library is an image processing library in Python. This library supports a wide range of file formats, is designed for an efficient internal representation of image data, and provides powerful image processing capabilities.
The ImageOps module
The ImageOps module in PIL contains ‘ready-made’ image processing operations and most operations only work on L (grayscale or single channel image) and RGB images.
The expand function
The expand function is used to add a border to the image.
Syntax
PIL.ImageOps.expand(image, border=0, fill=0)
Parameter
image: It is the image to expand or add the border to.border: It is the width of the border in pixels.fill: It is the border color.
Code example
Let’s look at the code below:
from PIL import Image, ImageOpsimg = Image.open('tree.png')img_with_border = ImageOps.expand(img, border=50, fill='red')img_with_border.save('output/tree-with-border.png')
Code explanation
- Line 1: We import the
ImageFilterandImagemodules. - Line 3: We read
man.pnginto memory usingopen()inImagemodule. - Line 5: We use the
expand()method and add a red color (fill) border of size30to the image. - Line 7: We then save the image with the border to the disk.