Created
November 18, 2018 08:12
-
-
Save fereria/3388ac0aa3f75724aa83b78a4348f8bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!python2 | |
# -*- coding: utf-8 -*- | |
from PIL import Image, ImageOps | |
from PIL.ExifTags import TAGS | |
import os.path | |
import re | |
import sys | |
image_dir = u"S:/blog_img/" | |
def get_exif_rotation(orientation_num): | |
""" | |
ExifのRotationの数値から、回転する数値と、ミラー反転するかどうかを取得する | |
return 回転度数,反転するか(0 1) | |
# 参考: https://qiita.com/minodisk/items/b7bab1b3f351f72d534b | |
""" | |
if orientation_num == 1: | |
return 0, 0 | |
if orientation_num == 2: | |
return 0, 1 | |
if orientation_num == 3: | |
return 180, 0 | |
if orientation_num == 4: | |
return 180, 1 | |
if orientation_num == 5: | |
return 270, 1 | |
if orientation_num == 6: | |
return 270, 0 | |
if orientation_num == 7: | |
return 90, 1 | |
if orientation_num == 8: | |
return 90, 0 | |
def get_exif_of_image(file): | |
"""Get EXIF of an image if exists. | |
指定した画像のEXIFデータを取り出す関数 | |
@return exif_table Exif データを格納した辞書 | |
:参考: https://www.lifewithpython.com/2014/12/python-extract-exif-data-like-data-from-images.html | |
""" | |
im = Image.open(file) | |
# Exif データを取得 | |
# 存在しなければそのまま終了 空の辞書を返す | |
try: | |
exif = im._getexif() | |
except AttributeError: | |
return {} | |
# タグIDそのままでは人が読めないのでデコードして | |
# テーブルに格納する | |
exif_table = {} | |
for tag_id, value in exif.items(): | |
tag = TAGS.get(tag_id, tag_id) | |
exif_table[tag] = value | |
return exif_table | |
def rotation_exif_info(path, to_path, resize=1.0): | |
""" | |
画像のexif情報を使用して、画像を回転する | |
""" | |
to_save_path = to_path + "/" + os.path.basename(path) | |
if os.path.exists(to_path) is False: | |
os.makedirs(to_path) | |
exif = get_exif_of_image(path) | |
rotate = 0 | |
reverse = 0 | |
if 'Orientation' in exif: | |
rotate, reverse = get_exif_rotation(exif['Orientation']) | |
img = Image.open(path) | |
data = img.getdata() | |
mode = img.mode | |
size = img.size | |
with Image.new(mode, size) as dst: | |
dst.putdata(data) | |
if reverse == 1: | |
dst = ImageOps.mirror(dst) | |
if rotate != 0: | |
dst = dst.rotate(rotate, expand=True) | |
x = int(dst.size[0] * resize) | |
y = int(dst.size[1] * resize) | |
img_resize = dst.resize((x,y),Image.LANCZOS) | |
img_resize.save(to_save_path) | |
def main(): | |
for i in sys.argv[1:]: | |
rotation_exif_info(i, u"S:/blog_img", 0.5) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment