• python练习册 每天一个小程序 第0005题


     1 # -*-coding:utf-8-*-
     2 __author__ = 'Deen'
     3 '''
     4 题目说明: 你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
     5 
     6 思路: 先获取该目录下所有图片的绝对路径,再一个一个打开,resiz改变大小保存
     7 '''
     8 
     9 from PIL import Image
    10 import os
    11 
    12 
    13 # 获取目录下所有图片的绝对路径
    14 def list_files(dir, wirldcard, recursion):
    15     files_text = list()
    16     exts = wirldcard.split(" ")
    17     files = os.listdir(dir)
    18     for name in files:
    19         fullname = os.path.join(dir, name)
    20         if (os.path.isdir(fullname) & recursion):
    21             list_files(fullname, wirldcard, recursion)
    22         else:
    23             for ext in exts:
    24                 if (name.endswith(ext)):
    25                     files_text.append(fullname)
    26                     break
    27     # print files_text
    28     return files_text
    29 
    30 
    31 def images_resize(imgs, width, height):
    32     n = 0
    33     for img in imgs:
    34         n += 1
    35         image = Image.open(img)
    36         out = image.resize((width, height), Image.ANTIALIAS)
    37         out.save(str(n) + '.jpg', 'jpeg')
    38 
    39 
    40 if __name__ == '__main__':
    41     dir = "E:\images"
    42     wildcard = ".jpg .png"
    43     images_resize(list_files(dir, wildcard, 1), 500, 500)
    44 
    45 '''
    46 参考代码:
    47 import os
    48 
    49 from PIL import Image
    50 
    51 def resize_image(image):
    52     im = Image.open(image)
    53     width, height = im.size
    54     if height > 1136 or width > 640:
    55         th = height / 1136
    56         td = width / 640
    57         ts = max(th, td)
    58         nh = int(height / ts)
    59         nw = int(width / ts)
    60         im = im.resize((nw, nh))
    61         im.save(image)
    62         print('Successfully resized %s. New width is %i, new height is %i.' % (image, nh, nw))
    63     else:
    64         print("There's no need to resize %s." % image)
    65 
    66 def main():
    67     for i in os.listdir():
    68         try:
    69             resize_image(i)
    70         except IOError:
    71             print("Oops! %s is not supported to make the change!" % i)
    72 
    73 if __name__ == '__main__':
    74     main()
    75 
    76 '''
  • 相关阅读:
    Page6:关于能控性、能观性、能测性及其判据(1)[Linear System Theory]
    Page5:状态转移矩阵及性质、连续线性系统离散化及其性质[Linear System Theory]
    java线程学习之notify方法和notifyAll方法
    java线程学习之wait方法
    java线程学习之synchronized关键字
    java线程学习之Sleep方法
    java线程学习之线程创建
    用javaScript获取页面元素值
    用javaScript对页面元素进行显示和隐藏
    JDBC工具类
  • 原文地址:https://www.cnblogs.com/deen-/p/7149404.html
Copyright © 2020-2023  润新知