# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import cStringIO
import logging
import qrcode
from PIL import Image, ImageDraw, ImageFont
from django.conf import settings
from django.http.response import HttpResponse
logger = logging.getLogger('django')
def qrcode_1(request):
buf = gen_qrcode(request.GET.get('id'), request.GET.get('to_name'),
request.GET.get('from_name'), request.GET.get('wish'),
request.GET.get('pic_type'), request.session.get('domain'))
return HttpResponse(buf.getvalue(), 'image/jpg')
def gen_qrcode(red_bag_id='', to_name='', from_name='', wish='', pic_type=1, domain='www.xxx.xxx'):
"""
生成红包卡片
:param red_bag_id:
:param to_name:
:param from_name:
:param wish:
:param pic_type:
:param domain:
:return:
"""
url_code = 'http://{domain}/{id}'.format(domain=domain, id=red_bag_id)
if settings.DEBUG:
url_code = 'http://172.16.12.94:8002/{0}'.format(red_bag_id)
# url_code = 'http://172.16.12.26:8003/{0}'.format(red_bag_id)
cav_img_name = 'redbag{0}.jpg'.format(red_bag_id)
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=5, border=3)
qr.add_data(url_code)
qr.make(fit=True)
img = qr.make_image()
img = img.convert("RGBA")
# 二维码中心logo
mid_icon = Image.open(settings.HB_DIR + "dun.png")
# 背景图片
back_img = Image.open(settings.HB_DIR + pic_type + ".jpg")
back_img = back_img.resize((750, 1294))
back_img = back_img.convert("RGBA")
# 卡片
cav_img = Image.new('RGBA', (750, 1294), (220, 220, 220))
# 给卡片增加背景图片
cav_img = Image.alpha_composite(cav_img, back_img)
img_w, img_h = img.size
factor = 4
size_w = int(img_w / factor)
size_h = int(img_h / factor)
icon_w, icon_h = mid_icon.size
if icon_w > size_w:
icon_w = size_w
if icon_h > size_h:
icon_h = size_h
mid_icon = mid_icon.resize((icon_w, icon_h), Image.ANTIALIAS)
w = int((img_w - icon_w) / 2)
h = int((img_h - icon_h) / 2)
mid_icon = mid_icon.convert("RGBA")
img.paste(mid_icon, (w, h), mid_icon)
# img.show()
# img.save(settings.HB_DIR + 'createlogo.jpg')
cav_img.paste(img, (260, 720))
ttfont_15 = ImageFont.truetype(settings.GNU_DIR + '/msyh.ttf', 15, encoding='utf-8')
ttfont_20 = ImageFont.truetype(settings.GNU_DIR + '/msyh.ttf', 20, encoding='utf-8')
ttfont_30 = ImageFont.truetype(settings.GNU_DIR + '/msyh.ttf', 30, encoding='utf-8')
draw = ImageDraw.Draw(cav_img)
draw.text((110, 200), to_name + ":", fill='#e93d2f', font=ttfont_30)
draw.text((170, 260), wish, fill='#e93d2f', font=ttfont_30)
draw.text((232, 1047), url_code, fill='#faf19f', font=ttfont_20)
draw.text((625, 1205), from_name, fill='#e6df9f', font=ttfont_30)
buf = cStringIO.StringIO()
# cav_img.save(settings.HB_DIR + cav_img_name)
cav_img.save(buf, 'png')
return buf
说明: 用程序写文字的时候,用画图工具测量距离。