本文實例講述了python使用Image處理圖片常用技巧。分享給大家供大家參考。具體分析如下:
使用python來處理圖片是非常方便的,下面提供一小段python處理圖片的代碼,需要安裝圖像處理工具包PIL(Python Image Library)。
#coding=utf-8import Imageimport urllib2import StringIOimport os#改變圖片大小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_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#處理遠(yuǎn)程圖片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 eif __name__ == '__main__': img_path = 'test.jpg' resize_img(img_path) change_img_type(img_path) img_url = 'http://img.hb.aicdn.com/042f8a4a70239f724ff7b9fa0fc8edf18658f41022ada-WcItWE_fw554' handle_remote_img(img_url)可能會遇到的問題
ImportError: No module named Image
解決辦法:安裝Python Imaging Library(PIL)
― ZLIB (PNG/ZIP) support not available
― FREETYPE2 support not available
操作jpeg圖片和png圖片出現(xiàn):
IOError: decoder jpeg not available 和 IOError: encoder zip not available
解決辦法:
(1) 刪除已經(jīng)安裝的PIL
― JPEG support available
― ZLIB (PNG/ZIP) support available
― FREETYPE2 support available
現(xiàn)在試試,已經(jīng)ok了
希望本文所述對大家的Python程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選