Python How to Convert Image Format Easily
Image.open() and save it in a new format with image.save('newfile.format').Examples
How to Think About It
Algorithm
Code
from PIL import Image # Open an existing image image = Image.open('input.jpg') # Save the image in a new format image.save('output.png') print('Image converted and saved as output.png')
Dry Run
Let's trace converting 'input.jpg' to 'output.png' through the code
Open image
image = Image.open('input.jpg') loads the image data from 'input.jpg'
Save image
image.save('output.png') writes the image data to 'output.png' in PNG format
Print confirmation
Prints 'Image converted and saved as output.png' to confirm success
| Step | Action | File |
|---|---|---|
| 1 | Open image | input.jpg |
| 2 | Save image | output.png |
| 3 | Print message | N/A |
Why This Works
Step 1: Open the image
The Image.open() function reads the image file and loads it into memory so it can be processed.
Step 2: Save in new format
The save() method writes the image data to a new file. The file extension tells Pillow which format to use.
Step 3: Confirm conversion
Printing a message confirms the program ran successfully and the new image file exists.
Alternative Approaches
import cv2 # Read image img = cv2.imread('input.jpg') # Write image in new format cv2.imwrite('output.png', img) print('Image converted and saved as output.png')
import imageio # Read image img = imageio.imread('input.jpg') # Write image in new format imageio.imwrite('output.png', img) print('Image converted and saved as output.png')
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of pixels (n) because the entire image data must be read and written.
Space Complexity
The space needed is proportional to the image size (n) as the image is loaded fully in memory.
Which Approach is Fastest?
Pillow is easy and sufficient for most uses; OpenCV can be faster for large images but is more complex to use.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Pillow | O(n) | O(n) | Simple scripts and common formats |
| OpenCV | O(n) | O(n) | Performance with large images |
| imageio | O(n) | O(n) | Simple multi-format support |
pip install pillow before running image conversion code.save() causes the image to save in the original format.