绘制验证码
from PIL import Image,ImageFilter,ImageFont,ImageDraw
import random
width=100
hight=100
im=Image.new('RGB',(width,hight),(255,255,255))
draw=ImageDraw.Draw(im)
#获取颜色
def get_color1():
return (random.randint(200, 255), random.randint(200, 255), random.randint(200, 255))
def getchar():
st='0123456789aAbBcCdDeEfFgGhHiIjjkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'
c=''
for i in range(4):
c+=random.choice(st)
return c
#填充每个像素
for x in range(width):
for y in range(hight):
draw.point((x,y),fill=get_color1())#使画布呈现五彩斑斓的样子
font = ImageFont.truetype('simsun.ttc', 36)
draw.text((10,50),getchar(),font=font,fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
im.filter(ImageFilter.GaussianBlur)
im.show()
你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
from PIL import Image
import os, imghdr
def photo_resize(path):
pw,ph = (1136, 640)#iphone5分辨率
f_list = os.listdir(path)#获取文件夹中的文件列表
for each in f_list:
f_path = path+'\\'+each#表示单反斜杠时需要反义
if imghdr.what(f_path):#判断是否是图片类型
img = Image.open(f_path)
w,h = img.size
if(w>pw):
img = img.resize((int(pw), int(h*(pw/w))))#resize返回的是一个img
w, h = img.size
if(h>ph):
img = img.resize((int(w*(ph/h)), int(ph)))#resize参数是一个包括两个整形变量的元组
img.save(f_path)
del img
if __name__ == "__main__":
photo_resize(".\dir")
绘制九宫格:
from PIL import Image, ImageFilter, ImageFont, ImageDraw
width=300;height=300
x,y=0,0
im = Image.new("RGB",(width,height),(255,255,255)) #最后一个参数是背景颜色,像素默认值
draw = ImageDraw.Draw(im)
def get_color1():
a = (x//100)+(y//100)
if a == 0:
return (255,0,0)
elif a == 1:
return (0,255,255)
elif a ==2:
return (0,0,255)
elif a==3:
return (255,255,0)
elif a==4:
return (255, 0, 255)
else:
return (0, 0, 0)
# 填充每个像素
for x in range(width):
for y in range(height):
draw.point((x, y), fill=get_color1())
im.show()