import os
import traceback
from PIL import Image
import os
import time
import whatimage
# import pyheif
from werkzeug.utils import secure_filename
from PIL import Image, ExifTags
import matplotlib.image as mpimg
save_img_path = 'image_after/'
def save_new_image_format(now_path, origin_img_file_path, to_format):
try:
im = Image.open(origin_img_file_path)
new_file_name = os.path.splitext(origin_img_file_path)[0].split('/')[-1] + to_format
new_save_path = os.path.join(now_path, save_img_path)
if not os.path.exists(new_save_path):
os.makedirs(new_save_path)
write_file_path = os.path.join(new_save_path, new_file_name)
print('write_file_path = ', write_file_path)
im.save(write_file_path)
except:
traceback.print_exc()
def resize_image_work(file_path, file_out, width=800, height=800):
"""
重置图片大小
"""
image = Image.open(file_path)
flag = False
w, h = image.size
# print('w = {} h = {} image.size = {}'.format(w, h, image.size))
# print('ExifTags.TAGS.keys() = {}'.format(ExifTags.TAGS.keys()))
try:
orientation = 0
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif = dict(image._getexif().items())
# print('exif = {}'.format(exif))
# print('exif。keys = {}'.format(exif.keys()))
if exif[orientation] == 3:
image = image.rotate(180, expand=True)
flag = True
elif exif[orientation] == 6:
image = image.rotate(270, expand=True)
flag = True
elif exif[orientation] == 8:
image = image.rotate(90, expand=True)
flag = True
lena = mpimg.imread(file_path)
if flag:
w, h = lena.shape
except:
w, h = image.size
finally:
# current_app.logger.info(" resize_info: {}, {}, {}".format(w, h, flag))
print(" resize_info: {}, {}, {}".format(w, h, flag))
# 判断宽度和高度
# 判断大小
# if w <= width and h <= height:
# return file_path
if (1.0 * w / width) > (1.0 * h / height): # 宽大于高
scale = 1.0 * w / width
new_image = image.resize((int(w / scale), int(h / scale)), Image.ANTIALIAS)
else:
scale = 1.0 * h / height
new_image = image.resize((int(w / scale), int(h / scale)), Image.ANTIALIAS)
# 保存图片
new_image = new_image.convert("RGB")
new_image.save(file_out)
return file_out
if __name__ == "__main__":
now_path = os.getcwd()
print('now_path = ', now_path)
origin_dir_name = '../inspiration/origin_inspiration'
origin_img_file_path = os.path.join(now_path, origin_dir_name)
print('origin_img_file_path = ', origin_img_file_path)
for root, dirs, files in os.walk(origin_img_file_path):
# print('root = ', root)
# print(dirs)
# print(files)
i = 1
for img_file_name in files:
img_file_path = os.path.join(root, img_file_name)
print('--------- img_file_path = {}'.format(img_file_path))
out_file_path = img_file_path.replace('origin_inspiration', 'inspiration_resize')
print('--------- out_file_path = {}'.format(out_file_path))
resize_image_work(img_file_path, out_file_path, width=800, height=800)
# 格式变化
# save_new_image_format(now_path, img_file_path, '.jpg')
print(i)
i += 1