[Python] 画像を圧縮

まず画像を用意します。

#! /usr/bin/python3
# -*- coding: utf-8 -*-
from PIL import Image
from io import BytesIO
import os

COMPRESS_QUALITY = 30

path = "./src"

images = os.listdir(path)

for image in images:
	if image.endswith('.jpg'):
		with open("./src/" + image, 'rb') as inputfile:
			im = Image.open(inputfile)
			im_io = BytesIO()
			im.save(im_io,'JPEG', quality=COMPRESS_QUALITY)
		with open("./src/comp_" + image, mode='wb') as outputfile:
			outputfile.write(im_io.getvalue())
	if image.endswith('.jpeg'):
		with open("./src/" + image, 'rb') as inputfile:
			im = Image.open(inputfile)
			im_io = BytesIO()
			im.save(im_io,'JPEG', quality=COMPRESS_QUALITY)
		with open("./src/comp_" + image, mode='wb') as outputfile:
			outputfile.write(im_io.getvalue())
	if image.endswith('.png'):
		with open("./src/" + image, 'rb') as inputfile:
			im = Image.open(inputfile)
			im_p = im.convert('P')
			with open("./src/comp_" + image, mode='wb') as outputfile:
				im_p.save(outputfile)

我ながらよく出来ています。