在一次工作中,需要對圖片進行處理,windows自帶的 畫圖 軟件達不到需要的要求,于是便自己寫了個小工具,在此分享:
首先在Python 環(huán)境安裝好的情況下 ,安裝PIL(Python Imaging Library)模塊
下面是一些使用
#coding=utf-8
import Image
import urllib2
import StringIO
import os
#改變圖片大小
def resize_img(img_path):
? try:
??? img = Image.open(img_path)
??? (width,height) = img.size
??? new_width = 1055
#???? new_height = height * new_width / width
??? new_height = 582
??? out = img.resize((new_width,new_height),Image.ANTIALIAS)
??? ext = os.path.splitext(img_path)[1]
??? new_file_name = '%s%s' %('new',ext)
??? out.save(new_file_name,quality=95)
? except Exception,e:
??? print e
#改變圖片類型
def change_img_type(img_path):
? try:
??? img = Image.open(img_path)
??? img.save('new_type.png')
? except Exception,e:
??? print e
#處理遠程圖片
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.open(img_buffer)
??? img.save('remote.jpg')
??? (width,height) = img.size
??? out = img.resize((200,height * 200 / width),Image.ANTIALIAS)
??? out.save('remote_small.jpg')
? except Exception,e:
??? print e
if __name__ == '__main__':
? img_path = 'boy.png'
? resize_img(img_path)
#?? change_img_type(img_path)
#?? img_url = 'http://img.hb.aicdn.com/042f8a4a70239f724ff7b9fa0fc8edf18658f41022ada-WcItWE_fw554'
#?? handle_remote_img(img_url)