pip3 install pillow
import PIL
img.html
<img src='/img/'>
url.py
from django.conf.urls import url
from django.contrib import admin
#主路由导入视图内函数
from app import views
urlpatterns = [
url(r'^img/', views.img),
url(r'^show/', views.show),
]
view.py
def show(request):
return render(request,'img.html')
def img(request)
with open('static/img/lhf.jpg','rb') as f:
data=f.read()
return HttpResponse(data)
from PIL import Image
def show(request):
return render(request,'img.html')
def img(request)
img=Image.new('RGB',(350,40),(123,222,222)) #颜色模式,长宽,rgb里面的颜色
#把图片保存起来
with open('static/img/code.png','wb') as f:
#把图片保存起来(注意,用img对象的save方法,把f传入)
img.save(f)
#打开返回
with open('static/img/code.png','rb') as f:
data=f.read()
return HttpResponse(data)
from PIL import Image
from io import BytesIO
def show(request):
return render(request,'img.html')
def img(request)
img=Image.new('RGB',(350,40),(123,222,222)) #颜色模式,长宽,rgb里面的颜色
#生成一个Byteio对象
f=BytesIO()
# #把文件保存到对象中
img.save(f,'png')
#f.getvalue() 把文件从对象中取出来
return HttpResponse(f.getvalue())
from PIL import Image
from io import BytesIO
def show(request):
return render(request,'img.html')
def img(request)
img=Image.new('RGB',(350,40),(123,222,222)) #颜色模式,长宽,rgb里面的颜色
#写文字
#生成一个字体对象
font=ImageFont.truetype('static/font/kumo.ttf',34) #字体文件路径,字体大小
# 调用方法,返回一个画板对象
draw=ImageDraw.Draw(img)
draw.text((0,10),'python',font=font) #字体的XY坐标,字体内容,字体类型
f=BytesIO()
img.save(f,'png')
return HttpResponse(f.getvalue())
from PIL import Image
from io import BytesIO
def show(request):
return render(request,'img.html')
def img(request)
img = Image.new('RGB', (350, 40), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 写文字
# 生成一个字体对象
font = ImageFont.truetype('/static/Gabriola.ttf', 34)
# 调用方法,返回一个画板对象
draw = ImageDraw.Draw(img)
new_text =''
# 生成随机8位数字
for x_index in range(1, 8):
num = chr(random.randint(48, 57))
word = chr(random.randint(65, 90))
word_1 = chr(random.randint(97, 122))
text =random.choice((num, word, word_1))
draw.text((x_index * 32, 0),text, font=font)
new_text +=text
# 加点线
width = 320
height = 35
for i in range(5):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
# 在图片上画线
draw.line((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
for i in range(33):
# 画点
draw.point([random.randint(0, width), random.randint(0, height)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
x = random.randint(0, width)
y = random.randint(0, height)
# 画弧形
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
print(new_text)
#存在session中
request.session['code']=new_text
#存内存
f = BytesIO()
img.save(f, 'png')
return HttpResponse(f.getvalue())