用于查找图像尺寸(分辨率)的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


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

大多数文件格式都有文件头(最初的几个字节),其中包含有关文件的有用信息。

例如,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 个字节转换为一个数字。最后,显示分辨率。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战