知识被分享才有意义
1. 安装
python2.x 执行 pip install PIL
python3.x 执行 pip3 install Pillow
2.图片缩放
from PIL import Image
image = Image.open('1.jpg')
#获取图像宽高
w,h = image.size
print('original image size :%sx%s' %(w,h))
#缩放
image.thumbnail((w//2,h//2))
print('thumbnial image size:%sx%s' %(w//2,h//2))
image.save('thumbnial.jpg','jpeg') ```
3.模糊图片
模糊图片主要用到ImageFilter 导入 from PIL import ImageFilter
```image = Image.open('thumbnial.jpg')
#图片模糊
image1 = image.filter(ImageFilter.BLUR)
image1.save('dim.jpg','jpeg') ```
4.动态生成验证码
生成动态验证码主要用到ImageDraw,ImageFont这两个类,导入
from PIL import ImageDraw,ImageFont
```
#随机字符串
def randomChar():
return chr(random.randint(65,90))
#随机rgb的值
def randomColor():
return(random.randint(32,127),
random.randint(10,127),random.randint(20,157))
def randomColor2():
return (random.randint(64,255),
random.randint(64,255),random.randint(64,255))
def drawRandomCode():
width = 60*4
height = 60
image = Image.new('RGB',(width,height),(255,255,255))
#创建font对象
font = ImageFont.truetype('Monaco.ttf',36)
#创建draw对象
draw = ImageDraw.Draw(image)
#填充像素
for x in range(width):
for y in range(height):
draw.point((x,y),fill=randomColor2())
for t in range(4):
draw.text((60*t+10,10),randomChar(),
font=font,fill=randomColor())
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg','jpeg')
```