python处理图片之PIL模块简单使用方法

yipeiwu_com6年前Python基础

本文实例讲述了python处理图片之PIL模块简单使用方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/env python  
#encoding: utf-8 
import Image  
class myimg: 
  def __init__(self, open_file, save_file): 
    self.img = Image.open(open_file) 
    self.save_file = save_file 
  def Change_Size(self, percent=100, height=None, width=None): 
    ''''' 
    percent:以百分比来决定大小 
    height, width:以指定的高、宽来决定大小 
    ''' 
    if not (height and width): 
      width,height = self.img.size   
    new_img = self.img.resize((width*percent/100,height*percent/100),Image.BILINEAR) 
    new_img.save(self.save_file) 
  def Rotation(self, angle): 
    ''''' 
    angle: 旋转的度数 
    ''' 
    rot_img = self.img.rotate(angle) #旋转 
    rot_img.save(self.save_file) 
  def Save_as(self, filename): 
    ''''' 
    filename: 另存为图片格式,直接根据后缀名来 
    ''' 
    self.img.save(filename)  
  def Draw_Something(self): 
    ''''' 
        利用ImageDraw来画图形 
    ''' 
    import ImageDraw 
    draw = ImageDraw.Draw(self.img) 
    width,height = self.img.size 
    draw.line(((0,0),(width-1,height-1)),fill=255) #画直线 
    draw.line(((0,height-1),(width-1,0)),fill=255) 
    draw.arc((0,0,width-1,height-1),0,360,fill=255) #画椭圆 
    self.img.save(self.save_file) 
  def Enhance_Something(self): 
    ''''' 
        利用 ImageEnhance来增强图片效果 
    ''' 
    import ImageEnhance 
    brightness = ImageEnhance.Brightness(self.img) 
    bright_img = brightness.enhance(2.0) ##亮度增强 
    bright_img.save(self.save_file) 
    sharpness = ImageEnhance.Sharpness(self.img) 
    sharp_img = sharpness.enhance(7.0) #锐度增强 
    sharp_img.save(self.save_file) 
    contrast = ImageEnhance.Contrast(self.img) #对比度增强 
    contrast_img = contrast.enhance(2.0)  
    contrast_img.save(self.save_file) 
if __name__ == "__main__": 
  file_name = r"D:\test.png" 
  save_file = r"D:\save.png" 
  saveas_file = r"D:\save_as.bmp" 
  oimg = myimg(file_name, save_file) 
  oimg.Change_Size(30) 
  oimg.Rotation(45) 
  oimg.Save_as(saveas_file) 
  oimg.Draw_Something() 
  oimg.Enhance_Something()

原图:

处理过的画图:(锐化过的)

PS:此外还有另一个比较常用的模块,image模块。

希望本文所述对大家的Python程序设计有所帮助。

相关文章

利用Python库Scapy解析pcap文件的方法

利用Python库Scapy解析pcap文件的方法

每次写博客都是源于纳闷,python解析pcap这么常用的例子网上竟然没有,全是一堆命令行执行的python,能用吗?玩呢? pip安装scapy,然后解析pcap: import...

python实现批量nii文件转换为png图像

之前介绍过单个nii文件转换成png图像: /post/165693.htm 这里介绍将多个nii文件(保存在一个文件夹下)转换成png图像。且图像单个文件夹的名称与nii名字相同。...

python实现支付宝当面付(扫码支付)功能

本文实例为大家分享了python实现支付宝当面付示的具体代码,供大家参考,具体内容如下 一、配置信息准备 登录蚂蚁金服开放平台:https://open.alipay.com/platf...

Python变量作用范围实例分析

本文实例讲述了Python变量作用范围。分享给大家供大家参考。具体如下: #coding=utf-8 #变量作用范围 global z #使用全局变量 z=1 #给全局变量赋值 x=...

django model去掉unique_together报错的解决方案

事情是这样的,我有一个存储考试的表 class Exam(models.Model): category = cached_fields.ForeignKeyField(Categ...