详解使用Python将文件从jpg转换成png

  • Post category:Python

Convert JPG to PNG using Python

Python provides many libraries to handle images. One of these libraries is Pillow. Pillow is an open-source image processing library that supports opening, manipulating, and encoding many image file formats.

Here is the step-by-step guide to convert a JPG file to a PNG file using Python:

  1. Install Pillow: Before starting the conversion, we need to install the Pillow module. To install Pillow, open the command prompt or terminal and enter the following command:
pip install Pillow
  1. Import the Pillow module: After installing the Pillow module, we need to import it into our Python script using the following code:
from PIL import Image
  1. Open the JPG file: Next, we need to open the JPG file using the open() method of the Image class. This method takes the file path as the parameter. Here’s an example:
img = Image.open("example.jpg")
  1. Convert the JPG file to PNG: To convert the JPG file to PNG, we need to use the save() method of the Image class. This method takes the file name and file format as parameters. Here’s an example:
img.save("example.png", "png")
  1. Close the file: Finally, we need to close the image file using the close() method. Here’s an example:
img.close()

Example:

from PIL import Image

# Open the JPG file
img = Image.open("example.jpg")

# Convert the JPG file to PNG
img.save("example.png", "png")

# Close the file
img.close()

Another example:

from PIL import Image
import os

# Convert all JPG files in a directory to PNG
for file_name in os.listdir("path/to/jpg/files"):
    if file_name.endswith(".jpg"):
        # Open the JPG file
        img = Image.open(f"path/to/jpg/files/{file_name}")

        # Convert the JPG file to PNG
        img.save(f"path/to/png/files/{os.path.splitext(file_name)[0]}.png", "png")

        # Close the file
        img.close()

In this example, we convert all the JPG files in a directory to PNG files and save them in another directory. The os.listdir() method is used to get all the file names in the directory. The os.path.splitext() method is used to separate the file name and extension. Finally, we use string formatting to generate the output file name.