python 图片处理-PIL(Python Imaging Library)

在一次工作中,需要对图片进行处理,windows自带的 画图 软件达不到需要的要求,于是便自己写了个小工具,在此分享:

首先在Python 环境安装好的情况下 ,安装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)

你可能感兴趣的:(python 图片处理-PIL(Python Imaging Library))