Python Pillow - 轉換影像檔案格式



使用 Python Pillow **轉換影像檔案格式** 非常簡單。您可以將影像以一種格式開啟,並將其儲存為另一種格式,並指定所需的輸出格式。此過程通常包括以下步驟:

  • **開啟源影像**:使用 **Image.open()** 函式開啟源影像。

  • **儲存影像**:使用 **save()** 方法以所需的格式儲存影像,並指定新的檔案格式和目標位置。

Pillow 可以識別並讀取 30 多種不同的格式。當使用 **open()** 函式時,Pillow 根據影像內容確定格式,而不僅僅是檔名。但是,當使用 **save()** 方法儲存影像時,它通常會檢視檔名以決定格式,除非您明確指定要使用哪種格式。

Pillow 支援的檔案格式

Pillow 支援各種影像格式的讀取和寫入。某些格式得到完全支援,這意味著您可以讀取和寫入這些格式的影像。這些包括流行的格式,如 JPEG、PNG、BMP、BLP、DDS、EPS、GIF、ICNS、ICO、MSP、PCX、PNG、PPM、SGI、TGA、TIFF、WebP 和 XBM。

此外,它還為一系列其他格式提供只讀和只寫支援。

  • **只讀格式:**CUR、DCX、FITS、FLI、FLC、FPX、GBR、GD、IMT、IPTC/NAA、MCIDAS、MIC、MPO、PCD、PIXAR、PSD、QOI、SUN、WAL 和 WMF/EMF。
  • **只寫格式:**PALM、PDF 和 XV 縮圖。

該庫還可以識別 BUFR、GRIB、HDF5 和 MPEG 等格式的影像格式。讓我們看看使用 Python Pillow 轉換影像檔案格式的示例。

示例

此示例將影像從 JPEG 格式轉換為 PNG 格式。

from PIL import Image

# Open the source image in JPEG format
image = Image.open("Images/logo.jpg")

# Convert and save the image in PNG format
image.save("output_image_PNG_format.png")
print("Image saved successfully in PNG format...")

輸出

Image saved successfully in PNG format...

示例

此示例將影像從 BMP 格式轉換為 GIF 格式。

from PIL import Image

# Open the source image in BMP format
image = Image.open("Images/lena.bmp")

# Convert and save the image in GIF format
image.save("output_image.gif")
print("Image saved successfully in GIF format...")

輸出

Image saved successfully in GIF format...

示例

此示例將影像從 GIF 格式轉換為 TIFF 格式。

from PIL import Image

# Open the source image in GIF format
image = Image.open("Images/Book_Animation.gif")

# Convert and save the image in TIFF format
image.save("output_image.tiff")
print("Image saved successfully in TIFF format...")

輸出

Image saved successfully in TIFF format...

示例

此示例將影像從 .bpm 檔案格式轉換為 .jpg 格式。

from PIL import Image

# Open the source image in BMP format
image = Image.open("Images/lena.bmp")

# Convert and save the image in JPEG format
image.save('lena_new.jpg')
print("Image saved successfully in JPEG format...")

輸出

Image saved successfully in JPEG format...

如果訪問儲存輸出影像的資料夾,您可以觀察生成的影像。

廣告