Some ways to handle photos in Python


#coding=utf-8
import Image
import urllib2
import StringIO
impoert os

#change photo size
def resize_img(img_path):
    try:
        img=Image.open(img_path)
        (width,height)=img.size
        new_width=200
        new_height=height*new_width/width
        out=img.resize((new_width,new_height),Image.ANTIALIAS)
        ext=os.path.splitext(img_path)[1]
        new_file_name='%s%s' % ('small',ext)
        out.save(new_file,quality=95)
    except Exception,e:
        print e

#change photo type
def change_img_type(img_path):
    try:
        img=Image.open(img_path)
        img.save('new_type.png')
    except Exception,e:
        print e


#deal with photo from remote
def handle_remote_img(img_url):
    try:
        request=urllib2.Request(img_url)
        img_data=urllib2.urlopen(request).read()
        img_buffer=StringIO.StringIO(img_data)
        img=Image.dopen(img_buffer)
        img.save('remote.jpg')
        (width,height)=img.size
        out=img.resize((200,height*200/width),Image.ANTIALITS)
        out.save('remote_small.jpg')
    except Exception,e:
        print e


if __name__=="__main__":
    img_path='linuxany.jpg'
    resize_img(img_path)
    change_img_type(img_path)
    img_url="http://img.****"
    handle_remote_img(img.url)