Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xác định loại hình ảnh với module imghdr trong Python

Module imghdr trong thư viện chuẩn xác định loại hình ảnh từ file hoặc byte stream.

Hàm duy nhất

imghdr.what(filename, h=None)
  • filename: đường dẫn file
  • h: byte stream (nếu cung cấp, filename bị bỏ qua)

Trả về string mô tả loại ảnh hoặc None.

Các định dạng hỗ trợ

Giá trịĐịnh dạng
'rgb'SGI ImgLib Files
'gif'GIF 87a và 89a
'pbm'Portable Bitmap
'pgm'Portable Graymap
'ppm'Portable Pixmap
'tiff'TIFF Files
'rast'Sun Raster Files
'xbm'X Bitmap Files
'jpeg'JPEG (JFIF/Exif)
'bmp'BMP Files
'png'Portable Network Graphics
'webp'WebP Files
'exr'OpenEXR Files

Ví dụ

import imghdr

print(imghdr.what('bass.gif'))    # 'gif'
print(imghdr.what('polar.png'))   # 'png'
print(imghdr.what('test.jpg'))    # 'jpeg'

# Từ byte stream
with open('test.jpg', 'rb') as f:
    data = f.read()
print(imghdr.what(None, h=data))  # 'jpeg'

Lưu ý

  • Chỉ kiểm tra header/magic bytes, không validate toàn bộ file
  • Hữu ích để filter file upload, xử lý batch ảnh
  • Python 3.11+ khuyến nghị dùng filetype hoặc python-magic thay thế