PNG 和 JPG 格式用於圖像插圖。這兩種格式都用於為某些類型的圖像提供良好的兼容性,例如 PNG 更適用於線條圖和圖標圖形,而 JPG 則適用於照片。但是,對於媒體和圖片的使用和存儲,兩者都可以相互轉換。 Python 提供了各種選項來執行圖像轉換。
方法一:Python 圖像庫(PIL)
Python 使用 PIL 包(Python Imaging Library)提供對圖像處理的支持。該庫提供了廣泛的文件格式支持,也就是說,它可用於將圖像從一種格式轉換為另一種格式。可以使用以下命令將此包安裝到環境中:
pip install Pillow
這個包提供了一個名為 Image 的模塊,用於創建新圖像並將其加載到環境中。它還允許使用圖像格式及其相關方向。它用於表示 PIL 圖像。相關的語法是:
from PIL import Image
Image 模塊的以下函數用於將圖像從 PNG 轉換為 JPG。
Image.open():打開並識別圖像文件。它不會加載文件,除非明確執行 load() 操作。它隻是打開圖像而不實際分析圖像內容。
PIL.Image.open(fp, mode='r', formats=None)
Arguments:
fp — Filename, pathlib.Path object or a file object.
mode — Always opened in reading mode.
formats — A list of formats to perform the opening operation of a file.
Return type:
An image object.
Image.save():以指定的文件名保存圖像。如果未指定擴展名,則從指定的文件名分析擴展名。
Image.save(fp, format=None, **params)
Arguments:
fp — Filename, pathlib.Path object or a file object.
format — Optional format.
params — Extra parameters to the image writer.
Return type:
Doesn’t return anything.
以下示例 Python 代碼用於將圖像從 PNG 轉換為 JPG:
Python3
#importing the required package
from PIL import Image
#open image in png format
img_png = Image.open('C:\gfg\img.png')
#The image object is used to save the image in jpg format
img_png.save('C:\gfg\modified_img.jpg')
輸出:
以下是 C 中的原始文件:
以下是程序執行後同一文件夾的內容:
方法二:使用 OpenCV
OpenCV(開源計算機視覺)庫是一個 image-processing 庫,它使用 MATLAB 語法執行數值運算。可以使用以下命令將其合並到我們的環境中:
pip install opencv-python
下載後可以使用命令將該庫導入python程序
import cv2
它為我們提供了各種操作圖像的函數,例如,imread() 函數將本地機器的圖像名稱作為參數,imwrite() 函數用於執行圖像的操作和修改。該方法具有以下簽名:
imwrite ( path, image)
Arguments:
path — A string representing the file name which must include the extension image format like .jpg, .png, etc.
image — The image that is to be saved.
Return type:
It returns true if the image is saved successfully.
Python3
#importing required packages and library
import cv2
# Loading .png image
png_img = cv2.imread('img.png')
# converting to jpg file
#saving the jpg file
cv2.imwrite('modified_img.jpg', png_img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
輸出:
以下目錄存儲名為 “img.png” 的圖像:
程序執行後得到如下輸出:
相關用法
- Node.js JPG轉PNG用法及代碼示例
- Node.js PNG轉JPG用法及代碼示例
- Java PNG Images轉JPEG用法及代碼示例
- Python Excel轉PDF用法及代碼示例
- Python binary轉string用法及代碼示例
- Python CSV轉JSON用法及代碼示例
注:本文由純淨天空篩選整理自yippeee25大神的英文原創作品 Convert PNG to JPG using Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。