本文實例講述了python使用Image處理圖片常用技巧。分享給大家供大家參考。具體分析如下:
使用python來處理圖片是非常方便的,下面提供一小段python處理圖片的代碼,需要安裝圖像處理工具包PIL(Python Image 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 = 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 #處理遠程圖片 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 = '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)
安裝PIL出現(xiàn):
― JPEG support not available
― 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
(2) 安裝相關庫
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/
(3) 重新安裝PIL
終端出現(xiàn):
― JPEG support available
― ZLIB (PNG/ZIP) support available
― FREETYPE2 support available
現(xiàn)在試試,已經(jīng)ok了
希望本文所述對大家的Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
