pip3 install pillow
html
import PILpython
img.html
django
<img src='/img/'>
url.py
session
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
app
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())