第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
思路:
1.如何打开文件目录,需要import os ,打开文件目录相关介绍见链接,链接
2.对于图片大小的处理,当大小超过iphone5的分辨率,进行等比例缩放。
代码如下:
#coding=utf-8
import os #打开文件时需要
from PIL import Image
import re
Start_path='F:/image/'
iphone5_width=1136
iphone5_depth=640
list=os.listdir(Start_path)
#print list
count=0
for pic in list:
path=Start_path+pic
print path
im=Image.open(path)
w,h=im.size
#print w,h
#iphone 5的分辨率为1136*640,如果图片分辨率超过这个值,进行图片的等比例压缩
if w>iphone5_width:
print pic
print "图片名称为"+pic+"图片被修改"
h_new=iphone5_width*h/w
w_new=iphone5_width
count=count+1
out = im.resize((w_new,h_new),Image.ANTIALIAS)
new_pic=re.sub(pic[:-4],pic[:-4]+'_new',pic)
#print new_pic
new_path=Start_path+new_pic
out.save(new_path)
if h>iphone5_depth:
print pic
print "图片名称为"+pic+"图片被修改"
w=iphone5_depth*w/h
h=iphone5_depth
count=count+1
out = im.resize((w_new,h_new),Image.ANTIALIAS)
new_pic=re.sub(pic[:-4],pic[:-4]+'_new',pic)
#print new_pic
new_path=Start_path+new_pic
out.save(new_path)
print 'END'
count=str(count)
print "共有"+count+"张图片尺寸被修改"
我想此代码不止适用于对于不大于iphone5分辨率的大小,适用于对于所有图片进行统一处理,所以我增加了标记,对于需要被更改的图片有提示,也保存了原图片,将更改后的图片命名更改为原图片名称加_new的新名称。也对更改的图片进行了计数。
在此,我有一个问题,
可以看到只是注释了print pic的区别,没有注释的就可以打印出之后的一句话,注释了的就不能打印出,没弄不明白为什么。