python批量重置圖片格式-批量重置圖片大小-壓縮圖片

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章