English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Python programme recherche la taille de l'image (résolution)

Complete Python Examples

In this example, you will learn how to find the resolution of jpeg images without using any external libraries

To understand this example, you should understand the followingPython programmingTopic:

JPEG(pronounced as “ jay-peg”)represents Joint Photographic Experts Group. It is one of the most widely used compression techniques for images.

Most file formats have headers (the first few bytes), which contain useful information about the file.

For example, the JPEG header contains height, width, color quantity (grayscale or RGB) and other information. In this program, we found the resolution of the JPEG images that read these headers without using any external libraries.

Source code to find the resolution of JPEG images

def jpeg_res(filename):
   """This function prints the resolution of the jpeg image file passed to it"""
   # Open the image, read in binary mode
   with open(filename,'rb') as img_file:
       # Image height (in2bytes as units) at164bits
       img_file.seek(163)
       # Read2bytes
       a = img_file.read(2)
       # Calculate height
       height = (a[0] << 8) + a[1]
       # The next two bytes are width
       a = img_file.read(2)
       # Calculate width
       width = (a[0] << 8) + a[1]
   print("The image resolution is", width, "x", height)
jpeg_res("img1.jpg")

Output results

The image resolution is 280 x 280

In this program, we opened the image in binary mode. Non-text files must be opened in this mode. The image height is at164bits, followed by the image width. Both are2bytes long.

Note that this only applies to the JPEG file interchange format (JFIF) standard. If your image is encoded using other standards (such as EXIF), the code will not work.

We use the bitwise shift operator << to2Convert bytes to numbers. Finally, display the resolution.

Complete Python Examples