Last modified: Apr 21, 2025 By Alexander Williams

Python Basic Image Formats Guide

Working with images is common in Python. This guide covers basic image formats like JPEG, PNG, and BMP. You will learn how to handle them using Python libraries.

Why Learn Image Formats in Python?

Images come in different formats. Each has unique features. Knowing them helps in tasks like image processing and classification.

Python offers tools like PIL and OpenCV. They make it easy to read, write, and convert images.

Common Image Formats

Here are the most used image formats:

  • JPEG: Best for photos. Uses lossy compression.
  • PNG: Supports transparency. Uses lossless compression.
  • BMP: Uncompressed format. Large file size.

Working with JPEG in Python

JPEG is popular for photos. Use the Pillow library to handle JPEG files.

 
from PIL import Image

# Open a JPEG image
img = Image.open("example.jpg")

# Display image info
print(img.format, img.size, img.mode)


JPEG (800, 600) RGB

This code opens a JPEG file. It prints format, size, and color mode.

Working with PNG in Python

PNG supports transparency. It is great for web graphics. Use the same Pillow library.

 
from PIL import Image

# Open a PNG image
img = Image.open("example.png")

# Save as JPEG
img.save("example_converted.jpg")

This converts a PNG to JPEG. Note that transparency is lost in JPEG.

Working with BMP in Python

BMP is uncompressed. It has large file sizes. Use Pillow to handle BMP files.

 
from PIL import Image

# Open a BMP image
img = Image.open("example.bmp")

# Save as PNG
img.save("example_converted.png")

This converts BMP to PNG. PNG reduces file size with lossless compression.

Comparing Image Formats

Each format has pros and cons:

  • JPEG: Small size but loses quality.
  • PNG
  • BMP: No compression. Best for editing.

Choose based on your needs. For rescaling, BMP or PNG is better.

Conclusion

Python makes it easy to work with image formats. Use Pillow for basic tasks. Understand each format's strengths.

For advanced tasks, explore libraries like OpenCV. Check our image processing guide for more.