Create an image format program using Pillow in Python3.3 Get to get width and height automatically
# ==================================================
#Image format
#
# -Specify the file name with the first argument
# -Specify the conversion format with the second argument
# ==================================================
# encoding: UTF-8
from PIL import Image #Image conversion module
import os, re, sys #File Path,Regular expression module,Because it uses command line arguments
###
# Main
#
def main():
#Argument check
if len(sys.argv) > 4:
fileName = sys.argv[1]
format = sys.argv[2]
#File open
img = Image.open(fileName, "r")
width, height = img.size
#Get before the file name extension,Change to file name after formatting
fileName = re.search("(?<!\.)\w+", fileName).group(0) + "." + format
#File existence check
flag = os.path.exists(fileName)
if flag == True:
print("The file already exists.")
sys.exit()
#Create and paste a canvas to paste the image on
canvas = Image.new("RGB", (width, height), (255, 255, 255))
canvas.paste(img, (0, 0))
#Save image
canvas.save(fileName, returnFormat(format), quality=100, optimize=True)
else:
print("There are too few arguments.\n Specify the file name and the format of the file to be converted.\
\n * Specify the format in lowercase.\
\n examples) python imgf.py fileName.jpg bmp 100 100")
###
# returnFormat()
#Returns the passed format in uppercase
#
def returnFormat(format):
if format == "bmp":
return "BMP"
elif format == "jpg":
return "JPEG"
elif format == "png":
return "PNG"
elif format == "gif":
return "GIF"
else:
print(format + "Does not support.")
sys.exit()
if __name__ == "__main__":
main()
Reference site http://librabuch.jp/2013/05/python_pillow_pil/ http://d.hatena.ne.jp/fgshun/20080922/1222095288
Recommended Posts