Diary

Python Script to Convert All JPEG Files in a Specified Directory to PNG Format

1 Mins read
# Python script to convert all JPEG files in a specified directory to PNG format
# Python 3
# pip install Pillow
#
# Command below does not delete original files
# python jpeg-png.py
#
# Command below deletes original files
# python jpeg-png.py rm=1


from PIL import Image
import os
import sys


def convert_jpeg_to_png(directory, remove_jpeg=False):
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith('.jpg') or file.lower().endswith('.jpeg'):
jpeg_path = os.path.join(root, file)
png_path = os.path.splitext(jpeg_path)[0] + '.png'


try:
image = Image.open(jpeg_path)
image.save(png_path, format='PNG')
print(f"{jpeg_path}を{png_path}に変換しました")


if remove_jpeg:
os.remove(jpeg_path)
print(f"{jpeg_path}を削除しました")
except Exception as e:
print(f"{jpeg_path}の変換に失敗しました: {e}")


# Get and specify current directory
current_directory = os.getcwd()


# Check command line arguments
remove_jpeg = False
if len(sys.argv) > 1 and sys.argv[1] == 'rm=1':
remove_jpeg = True


convert_jpeg_to_png(current_directory, remove_jpeg)
Read more
Diary

Python script to convert all PNG files in a specified directory to JPEG format

1 Mins read
Python script to convert all PNG files in a specified directory to JPEG format
# Python script to convert all PNG files in a specified directory to JPEG format
# python3
# pip install Pillow
#
# Don't delete the file below
# python png-jpeg.py
#
# Delete the file below
# python png-jpeg.py rm=1


from PIL import Image
import os
import sys


def convert_png_to_jpeg(directory, remove_png=False):
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith('.png'):
png_path = os.path.join(root, file)
jpeg_path = os.path.splitext(png_path)[0] + '.jpg'


try:
image = Image.open(png_path)
rgb_im = image.convert('RGB')
rgb_im.save(jpeg_path, quality=100)
print(f"{png_path}を{jpeg_path}に変換しました")


if remove_png:
os.remove(png_path)
print(f"{png_path}を削除しました")
except Exception as e:
print(f"{png_path}の変換に失敗しました: {e}")


# Get and specify the current directory
current_directory = os.getcwd()


# Check command line arguments
remove_png = False
if len(sys.argv) > 1 and sys.argv[1] == 'rm=1':
remove_png = True


convert_png_to_jpeg(current_directory, remove_png)

 

Read more