Python Pillow - 影像檔案識別



使用 Python Pillow (PIL) 庫識別影像檔案涉及檢查副檔名以確定檔案是否可能是影像。雖然 Pillow 本身沒有內建方法來識別影像檔案,但我們可以使用 **os** 模組的函式,例如 **listdir()、path.splitext()、path.is_image_file()、path.join()**,根據使用者的需求根據副檔名過濾檔案。

Python 的 **os.path** 模組沒有提供直接的 **is_image_file()** 函式來識別影像檔案。相反,我們通常可以使用 Pillow 庫 (PIL) 來檢查檔案是否為影像。

但是,我們可以使用 **os.path** 並結合 Pillow 建立一個自定義的 **is_image_file()** 函式,根據檔案的副檔名來檢查檔案是否似乎是影像。

以下是如何使用 **os.path** 檢查副檔名並確定檔案是否可能是影像檔案的示例:

  • 我們定義了 **is_image_file()** 函式,它首先檢查副檔名是否看起來是常見的影像格式(在“image_extensions”中定義)。如果副檔名未被識別,則假定它不是影像檔案。

  • 對於識別的影像副檔名,該函式嘗試使用 Pillow 的 **Image.open()** 將檔案作為影像開啟。如果此操作成功且沒有錯誤,則該函式返回 **True**,表示該檔案是有效的影像。

  • 如果開啟檔案時出現問題,則該函式返回 **False**。

  • 此方法結合了 **os.path** 用於提取副檔名,以及 Pillow 用於檢查檔案是否為有效影像。

示例

import os
from PIL import Image
def is_image_file(file_path):
   image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico"}  
#Add more extensions as needed
   _, file_extension = os.path.splitext(file_path)

#Check if the file extension is in the set of image extensions
    return file_extension.lower() in image_extensions
file_path = "Images/butterfly.jpg"
if is_image_file(file_path):
   print("This is an image file.")
   Image.open(file_path)
else:	
   print("This is not an image file.")

輸出

This is an image file.

示例

在此示例中,我們傳遞副檔名為 **pdf**,因為它不是影像副檔名,因此結果將不是影像檔案。

import os
from PIL import Image
def is_image_file(file_path):
   image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico"}  
#Add more extensions as needed
   _, file_extension = os.path.splitext(file_path)

#Check if the file extension is in the set of image extensions
   return file_extension.lower() in image_extensions
file_path = "Images/butterfly.pdf"
if is_image_file(file_path):
   print("This is an image file.")
   Image.open(file_path)
else:
   print("This is not an image file.")

輸出

This is not an image file.
廣告