Whether it's adding captions, resizing or enhancing, I will demonstrate how you can edit images in bulk using Python in under 20 lines of code.
First, install Pillow:
pip3 install Pillow
Create a new Python file and place it where it can access your image folder. You can do this by either moving the image folder into your Python file's directory or moving the Python file into your image folder's parent directory.
You will also have to create a new folder next to your image folder for saving the edited images. I will call the folder "edited" but you can call it whatever you want.
Open your Python file and make the following imports:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import os
Once that's done, add the following to your Python file.
for g in range(len(os.listdir("photos"))):
Using this for loop, you'll be able to automatically edit every image in your folder.
Now, add the following code into your for loop in order to load the images.
imgstr = str(os.listdir("photos")[g])
img = Image.open("photos/"+imgstr)
Then add the following code to enhance your images.
converter = ImageEnhance.Color(img)
img2 = converter.enhance(0.1)
This will give your images the black/white effect. This is just an example. You can edit your images in other ways such as adding captions or changing size.
You can refer to the official documentation for more methods.
Finally, you should add the following into your for loop to save the edited versions of your images into your "edited" folder.
img2 = converter.enhance(0.1)
img2.save("edited/"+str(imgstr[:imgstr.index(".")]+str(".png")))
You probably noticed that I made the img2.save()
function save the edited images in the .png
format. This is because color enhancements are only compatible with .gif
and .png
images. As far as I'm aware, you only need to convert the images into .png
or .gif
when you're enhancing its color, but if you see the following error when editing your images in other ways, just know that you need to convert them either into .png
or .gif
.
OSError: cannot write mode RGBA as JPEG
Full Code
from PIL import Image,ImageEnhance
from PIL import ImageFont
from PIL import ImageDraw
import os
for g in range(len(os.listdir("photos"))):
imgstr = str(os.listdir("photos")[g])
img = Image.open("photos/"+imgstr)
converter = ImageEnhance.Color(img)
img2 = converter.enhance(0.1)
img2.save("edited/"+str(imgstr[:imgstr.index(".")]+str(".png")))
Top comments (1)
Great Code!!!!