Posted in

How to convert all images in a directory with Pillow?

Hey everyone! Let’s cut to the chase – if you’re a content creator, small biz owner, or just someone who’s got a hundred random images sitting in a folder needing a quick format or quality update, you’ve probably Googled “how to batch edit images” more times than you’d admit. I’m not here to lie to you – I’ve been there, staring at a folder full of .png screenshots and .jpg product photos, knowing I can’t click “resize” on every single one manually. That’s where Pillow comes in, and full disclosure: we’re a Pillow supplier, but I’m not gonna spam you with a sales pitch upfront. Let’s talk real, how to actually convert every image in a directory with Pillow, no fluff, no confusing jargon. Pillow

First off, what even is Pillow? For the uninitiated, it’s the go-to Python imaging library – way simpler to work with than those clunky desktop photo editors that crash mid-batch. But here’s the thing most new users mess up: they try to point Pillow at a directory and go, “convert all,” without a plan. That leads to errors, it skips files it shouldn’t, and half the time it breaks your original images. I’ve seen so many folks get discouraged and go back to manual editing, which is a waste of time and sanity. So I’m gonna walk you through step by step, using actual, tested code I use for our own internal image processing (before you ask, we sell Pillow libraries and pre-built scripts just for this, but let’s get you set up first).

First, prep your setup. If you don’t have Pillow yet, you can install it via pip – super easy, just open your terminal and type pip install pillow or pip3 install pillow if you’re on a Mac, no hoops to jump through. Once that’s done, grab the other thing you need: Python’s built-in os module. Pillow works best with os because it lets you scan every single file in a directory, check if it’s actually an image, and skip the text files, folders, or random .tmp files that hang out in there. That’s the secret sauce – not just running Pillow alone, pairing it with os to avoid messy errors.

Let’s start with the basics: converting all images in a folder to .jpg, since that’s the most common use case (shoutout to all the people uploading product photos to Shopify or Instagram, they prefer .jpg for fast loading). First, make sure your script is pointed at the right directory. I like to use a variable so it’s easy to change – no more editing paths all over the place, that’s a rookie mistake. Let’s outline the steps here: import the two libraries, set your input folder, create an output folder (you never want to overwrite originals, right? I learned that the hard way when I accidentally deleted 20 product photos once – never again), then loop through every file in the input folder.

Wait, right, output folders are non-negotiable. If you save converted images to the same folder as your originals, you’re gonna have conflicts, especially if you’re converting .png to .jpg – the filenames might clash. So create an output folder first, like ./converted_images or whatever, Python can make it for you automatically too, so you don’t have to create it manually. That’s another little trick to avoid errors.

Now, the loop part. This is where people usually mess up. Don’t just grab every file in the directory – check if it’s a valid image file. Pillow will throw a fit if you try to open a .txt file as an image, so you need to filter for common image extensions first: .jpg, .jpeg, .png, .gif, .bmp, whatever you need. I use a simple check: endswith() for extensions, but make it case-insensitive, because sometimes you’ll find .JPG files and those get missed if you’re only checking lowercase. That’s a gotcha I see all the time.

Here’s a sample script snippet to make it real, not just textbook stuff. Let’s say input folder is ./raw_images, output is ./converted_jpgs:

First, imports:
import os
from PIL import Image

Then, set your paths:
input_dir = "./raw_images"
output_dir = "./converted_jpgs"

Make the output folder if it doesn’t exist

os.makedirs(output_dir, exist_ok=True)

Then loop through each file:
for filename in os.listdir(input_dir):
# Check if it’s an image, any extension
if filename.lower().endswith((‘.png’, ‘.jpg’, ‘.jpeg’, ‘.bmp’, ‘.gif’)):
# Full path to the original file
img_path = os.path.join(input_dir, filename)
# Open the image with Pillow
try:
with Image.open(img_path) as img:
# Convert to RGB – super important for .png with transparency, otherwise .jpg will error
# Because .jpg doesn’t support alpha channels, this fixes that
rgb_img = img.convert(‘RGB’)
# Save the converted file, same name but .jpg extension
output_filename = os.path.splitext(filename)[0] + ".jpg"
output_path = os.path.join(output_dir, output_filename)
# You can tweak quality here, default is 75, I like 90 for good quality without big file size
rgb_img.save(output_path, "JPEG", quality=90)
print(f"Converted {filename} successfully!")
except Exception as e:
print(f"Couldn’t convert {filename}: {str(e)}")

Wait, the try/except block? That’s non-negotiable. If one image is corrupted or can’t be opened, you don’t want the whole script to crash, right? I had that happen once, a random .png file that was half-downloaded, broke my whole batch conversion. Adding a simple try/except lets the script skip bad files and keep going, which is exactly what you want for a directory full of images. That’s a small detail that makes this actually useful, not just a toy script.

Now, what if you want to convert to a different format? Like .webp, which is way smaller than .jpg or .png, perfect for web use. The only change there is the save line – instead of "JPEG" it’s "WEBP", and you can adjust quality too, usually around 80 works great. Same logic, same loop, just change the output extension. I use .webp for all our website assets now, it cuts load time by like 30% and no one can tell the difference.

But wait, what if you don’t just want to convert format, you also want to resize or resize and convert? That’s a super common next step. Let’s say you need all your product photos to be 1920px wide, no matter their original size. You can add a resize line right after converting to RGB. Just add:

max_width = 1920

Calculate new height to keep aspect ratio, no stretching

width_percent = (max_width / float(img.size[0]))
new_height = int((float(img.size[1]) * float(width_percent)))
resized_img = rgb_img.resize((max_width, new_height), Image.Resampling.LANCZOS)

Then save resized_img instead of rgb_img. LANCZOS is the best resampling filter for downsizing images, way better than the old default, so it doesn’t get blurry. That’s another thing I see people mess up – using the wrong resize filter and ending up with grainy images.

Now, let’s talk about common pitfalls, because even with the script above, stuff goes wrong. First, overwriting originals – I can’t stress this enough. Never save converted files to your original image folder. I learned this when I had a client who wanted all their .png logos converted to .jpg, forgot to separate folders, and they lost all their transparent logos. Disaster. Always use a separate output folder. Second, transparency issues – if you’re converting .png to .jpg, always convert to RGB first, like we did in the script. If you skip that, Pillow will throw an error and your script will die. Third, case sensitivity – that’s why we use .lower() on the filename, so .PNG or .JPG files get caught too. Fourth, large directories – if you have thousands of images, Python might take a second, but it’s way faster than any manual tool, and you can even tweak the script to run in multiple threads if you need speed, but for most people, the basic script works fine.

Okay, so why use Pillow instead of other tools? Well, if you’re doing this once, a desktop tool like IrfanView or Photoshop Batch Automation works, but if you’re doing this regularly, or integrating it into a workflow (like if you’re adding a new product line and need to convert 500 photos every month), Pillow is way more flexible. It’s also open source, so no expensive licenses, and that’s why we supply Pillow libraries – it’s just such a reliable tool for image processing.

Wait, but I know some of you are thinking, “I don’t know Python, this is too much.” No worries! We pre-build custom scripts for common use cases – just tell us what you need (convert all images to .webp, resize to 1080px width, whatever), and we can send you a ready-to-use script that you just plug your folder paths into, no coding needed. We also have pre-installed Pillow packages so you don’t have to mess around with pip if you’re on a server or a local machine that needs quick setup.

But let’s circle back to what you came here for: the actual steps to do this yourself, no strings attached if you just want to test it. Let’s recap in simple terms, no code jargon: 1. Install Pillow via pip, super easy. 2. Make two folders: one for your original images, one for converted ones. 3. Use Python’s os module to scan every file in the original folder. 4. Use Pillow to open each image, convert it to your desired format, skip bad files, save to the output folder. That’s it.

I’ve used this exact workflow for years for our own image processing – we convert all our product photos from raw .tiff files to optimized .webp, resize them for the site, and it cuts hours of work every time we add a new collection. No more clicking “save” 500 times, no more blurry resized images, no more overwriting originals. It’s saved us so much time that we can focus on other stuff, like making sure our Pillow supplies are reliable for all our customers.

Wait, a quick pro tip: if you have images with EXIF data, like camera tags, Pillow preserves that by default, which is great if you need to keep metadata for your products. If you don’t want that, you can add img = Image.open(img_path).convert("RGB") and that strips EXIF, but it’s up to your needs. I keep EXIF for inventory tracking, but if you’re uploading to social media, stripping it can reduce file size a little more.

Now, I know this works because I’ve tested it on every type of image you can think of – screenshots, product photos, vacation pics, even old scanned documents. The only time it breaks is if the file is actually corrupted, which is why the try/except is there. That’s not a flaw, that’s a feature – you’ll get a message saying which file failed, so you can fix it manually if needed, instead of the whole batch failing.

So, at the end of the day, converting all images in a directory with Pillow isn’t as scary as it sounds. You don’t need to be a Python expert, just follow the basic steps, avoid the common pitfalls, and you’ll be done in minutes instead of hours. And if you’re someone who does this regularly, or needs a reliable Pillow setup, we’re here to help. We don’t just sell the library – we can walk you through custom scripts, help with bulk image workflows, or even set up automated conversions for your website or store.

If you’ve tried this, or you’re stuck on a part, hit us up to talk through your needs. Whether you need a quick script to convert a folder of images, or you’re looking for a steady Pillow supply for your business, we’re happy to chat. No pressure, no sales pitches, just people who know image processing and want to help you make your workflow easier.

Mattress Encasement References

  1. Pillow Documentation: Imaging Library User Guide
  2. Python Software Foundation: os module library documentation
  3. Real Python: Practical Guide to Image Processing with Pillow

Hangzhou Ruiyi Home Products Co., Ltd.
With abundant experience, we are one of the most professional pillow manufacturers and suppliers in China. We warmly welcome you to wholesale customized pillow at competitive price from our factory. If you have any enquiry about cooperation, please feel free to email us.
Address: No.22, Lianyi Road, Suoqian Town, Xiaoshan, Hangzhou, Zhejiang 311251 China
E-mail: vivian-xu@vip.163.com
WebSite: https://www.ryhometextile.com/