📜  在Python中使用 Pillow 将图像转换为 jpg 格式

📅  最后修改于: 2022-05-13 01:55:47.449000             🧑  作者: Mango

在Python中使用 Pillow 将图像转换为 jpg 格式

让我们看看如何在Python中将图像转换为 jpg 格式。与 jpg 格式相比,png 的大小更大。我们还知道,某些应用程序可能会要求较小尺寸的图像。因此需要从 png(larger) 到 jpg(smaller) 的转换。
对于这个任务,我们将使用 Pillow 模块的Image.convert()方法。

算法 :

  1. 从 PIL 导入 Image 模块并导入 os 模块。
  2. 使用Image.open()方法导入要转换的图像。
  3. 使用os.path.getsize()方法显示转换前的图像大小。
  4. 使用Image.convert()方法转换图像。传递"RGB"作为参数。
  5. 使用Image.save()方法导出图像。
  6. 使用os.path.getsize()方法显示转换后的图像大小。

我们将转换以下图像:

# importing the module
from PIL import Image
import os
  
# importing the image 
im = Image.open("geeksforgeeks.png")
print("The size of the image before conversion : ", end = "")
print(os.path.getsize("geeksforgeeks.png"))
  
# converting to jpg
rgb_im = im.convert("RGB")
  
# exporting the image
rgb_im.save("geeksforgeeks_jpg.jpg")
print("The size of the image after conversion : ", end = "")
print(os.path.getsize("geeksforgeeks_jpg.jpg"))

输出 :

The size of the image before conversion : 26617
The size of the image after conversion : 18118