Python代码 在线执行

Python 程序:查找图像的大小(分辨率)

/examples/resolution-image

在此示例中,您将学习如何找到 jpeg 图像的分辨率,而无需使用外部库

要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:


JPEG(发音为“jay-peg”)代表联合图像专家组。 它是用于图像压缩的最广泛使用的压缩技术之一。

大多数文件格式都有标头(头几个字节),这些标头包含有关文件的有用信息。

例如,jpeg 标头包含高度,宽度,颜色数(灰度或 RGB)等信息。在此程序中,我们无需使用任何外部库即可找到读取这些标头的 jpeg 图像的分辨率。

查找 JPEG 图像分辨率的源代码

def jpeg_res(filename):
   """"This function prints the resolution of the jpeg image file passed into it"""

   # open image for reading in binary mode
   with open(filename,'rb') as img_file:

       # height of image (in 2 bytes) is at 164th position
       img_file.seek(163)

       # read the 2 bytes
       a = img_file.read(2)

       # calculate height
       height = (a[0] << 8) + a[1]

       # next 2 bytes is width
       a = img_file.read(2)

       # calculate width
       width = (a[0] << 8) + a[1]

   print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg") 

输出

The resolution of the image is 280 x 280

在此程序中,我们以二进制模式打开了图像。 非文本文件必须在此模式下打开。 图像的高度在第 164 位,然后是图像的宽度。 两者均为 2 个字节长。

请注意,这仅适用于 JPEG 文件交换格式(JFIF)标准。 如果您的图像是使用其他标准(例如 EXIF)编码的,则该代码将无法正常工作。

我们使用按位移位运算符<<将 2 个字节转换为数字。 最后,显示分辨率。