English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, you will learn how to find the resolution of jpeg images without using 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 image compression.
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.
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) at the164bits 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 in the164bits, 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 bit shift operator << to2Convert bytes to numbers. Finally, display the resolution.