转换图片尺寸

你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
原始文件

可以知道iPhone5的分辨率是1136*640.

这次刚好采用oop方式做一下,顺便也试试Python的log功能,
我准备了一个目录,里面放的是windows下的横屏壁纸,那么要转换成iPhone的竖屏壁纸当然是需要裁剪了,那就从中间裁吧。

__author__ = 'zynick'

#你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。

import glob
import os
import time
from PIL import Image
import logging

class picResize():
    """
    将指定目录下的图片文件转换为指定分辨率后保存在新目录
    """
    def __init__(self,path,folder_name):
        self.path = path
        self.folder_name = folder_name
        logging.basicConfig(filename = os.path.join(os.getcwd(), 'e:/log.log'), level = logging.DEBUG)

    def find_pics(self,path):
        # 根据路径获取图片
        pic_list = []
        for files in glob.glob(path + "/*.jpg"):
            file_path,file_name = os.path.split(files)
            pic_list.append(file_name)
            logging.log(logging.DEBUG,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" find:"+file_name)

        return pic_list

    def find_new_path(self,folder_name):
        # 寻找和创建文件保存路径
        folder = self.path + '/' + folder_name
        logging.log(logging.DEBUG,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" get path:"+folder)
        if not os.path.isdir(folder):
            os.mkdir(folder)

        return folder

    def process(self,pic_name,height,width):
        # 处理图片
        img = Image.open(pic_name)
        img_width,img_height = img.size
        #只考虑桌面壁纸那种宽比高长的图片
        var = img_width/img_height
        new_width = int(var*img_height)
        img = img.resize((new_width,height),Image.ANTIALIAS)
        padding = int((img_width-width)/2)
        box = (padding,0,padding+width,height)
        img = img.crop(box)
        logging.log(logging.DEBUG,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"crop success")
        return img


    def resize(self,height,width):
        # 开始工作
        pic_list = self.find_pics(self.path)
        output_folder = self.find_new_path(self.folder_name)
        outPut_file = ''
        try:![](http://)
            for pic in pic_list:
                pic_path = self.path+'/'+pic
                outPut_file = output_folder+'/output-'+pic
                output_file_model = self.process(pic_path,height,width)
                output_file_model.save(outPut_file,'JPEG')
                logging.log(logging.DEBUG,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" output:"+outPut_file)
        except:
            logging.log(logging.ERROR,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"Error in saving:"+outPut_file+"-")


def main():
    pic_Resize = picResize('e:/pics','output')
    pic_Resize.resize(1136,640)
    logging.log(logging.INFO,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"--finish--")

if __name__ == '__main__':
    main()

输出

输出
日志
日志

其实真正的算法部分很不严谨,但是考虑到只是简单的转换一下,图片应该先判断横竖关系,然后再看比例是否合适才能进行裁剪。