Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add prompt text to QR Code Picture with Python

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Python to add prompt text to QR code picture", the content of the explanation in the article is simple and clear, easy to learn and understand, now please follow the idea of Xiaobian slowly in depth, together to study and learn "how to use Python to add prompt text to QR code picture"!

Demand:

Determine whether the current browser is Wechat, if yes, provoke WeChat Pay, if not, display the QR code picture and prompt the user to open it in Wechat

Code implementation:

1. Judge whether Wechat or not

# toolbox.pyfrom typing import Any class UserAgent: def _ init__ (self, user_agent: str ='', request: Any = None): if request is not None: try: user_agent = request.headers.get ('user-agent','') # For Sanic except AttributeError: user_agent = request.META.get ('HTTP_USER_AGENT' '') # Django self.user_agent = user_agent @ property def is_alipay (self)-> bool: return "AlipayClient/" in self.user_agent @ property def is_wechat (self)-> bool: return "MicroMessenger/" in self.user_agent @ property def is_qq (self)-> bool: return "QQ/" in self.user_agent @ property Def scan_type (self)-> str: if self.is_wechat or self.is_qq: return "wechat" if self.is_alipay: return "alipay" return "unknown

two。 Add text to a picture

# image_text.py "" add text Usage:: > from xxx import deco_image > deco_image (image_path, text) # replace the old picture > deco_image (image_path, text, new_path, color='red') # keep the old picture and specify the text color "" from pathlib import Pathfrom typing import Optional, Tuple, Union from PIL import Image, ImageDraw " ImageFont # pip install pillow TIP = please use Wechat to scan the code to pay or share to Wechat. Open "# get picture width def get_img_width (fname)-> int: return Image.open (fname). Size [0] # get picture height def get_img_height (fname)-> int: return Image.open (fname). Size [1] # add text to the picture # generate blank_img blank image Add text to generate a new picture or overwrite the old picture with the width of the origin_img original picture MARGIN_LEFT, MARGIN_TOP = 50, 15FONT_SIZE = 22FONT_COLOR = "red" def gen_text_img (origin_img: Union [Path, str], text: str, img_path=None, color=FONT_COLOR, font_size: int = FONT_SIZE, margin_left: int = MARGIN_LEFT, margin_top: int = MARGIN_TOP Blank_img=None, font_path: Optional [str] = None, show_img: bool = False,)-> Union [Path, str]: width = get_img_width (origin_img) if blank_img is None: blank_img= Path (f "/ tmp/blank- {width} .png") elif isinstance (blank_img Str): blank_img = Path (blank_img) if not blank_img.exists (): Image.new ("RGB", (width, 70), (255,255) Save (blank_img) im = Image.open (blank_img) draw = ImageDraw.Draw (im) if font_path is None: # font_path = r "C:WindowsFontssimsun.ttc" # font_path = "/ System/Library/Fonts/Supplemental/Songti.ttc" font_path = "/ usr/share/fonts/truetype/windows-font/Songti.ttc" fnt = ImageFont.truetype (font_path Font_size) draw.text ((margin_left, margin_top), text, fill=color, font=fnt) if img_path is None: img_path = Path (origin_img) img_path = img_path.with_name (f "{img_path.stem}-{len (text)} {img_path.suffix}") im.save (img_path) if show_img: im.show () return img_path # Mosaic Image Splice the text and picture generated above to the original image # to generate a picture of the same width A blank long picture with a height of the sum of two pictures # open the picture and paste it into the blank long picture def join_imgs (text_img, origin_img, new_path=None)-> None: W = get_img_width (text_img) fh = get_img_height (text_img) oh = get_img_height (origin_img) blank_long_img = Image.new ("RGBA", (w) Fh + oh) # Blank figure font_img = Image.open (text_img). Resize ((w, fh), Image.ANTIALIAS) blank_long_img.paste (font_img, (0,0)) img1 = Image.open (origin_img). Resize ((w, oh), Image.ANTIALIAS) blank_long_img.paste (img1, (0) Fh)) if new_path is None: new_path = origin_img blank_long_img.save (new_path) blank_long_img.show () def deco_image (fpath: Union [Path, str], # Image path text: str = TIP, # text to add new_path: Union [Path, str, None] = None # path to save the new image (overrides the original image by default) color: Union [str, Tuple [int, int, int]] = FONT_COLOR, # text color font_size: int = FONT_SIZE, # text height margin_left: int = MARGIN_LEFT, margin_top: int = MARGIN_TOP,)-> None: text_img = gen_text_img (fpath, text, color=color Font_size=font_size, margin_left=margin_left, margin_top=margin_top,) join_imgs (text_img, fpath)

3. If the system is short of fonts, you need to download them

Sudo mkdir / usr/share/fonts/truetype/windows-fontsudo chmod 777 / usr/share/fonts/truetype/windows-fontcd / usr/share/fonts/truetype/windows-fontwget https://gitee.com/waketzheng/carstino/attach_files/703450/download/Songti.ttc # this file is large and has 66.9MB

4. Adjust the payment or generate a picture

From pathlib import Pathfrom hashlib import md5 import qrcode # pip install qrcodefrom sanic import Blueprintfrom sanic.log import loggerfrom sanic.request import Requestfrom sanic.response import json from .models import Orderfrom .image _ text import deco_imagefrom .toolbox import UserAgentfrom .utils import async_http_post, get_hostfrom .consts import URL_PREFIX, WX_PAY_URL bp = Blueprint ("epay", url_prefix=URL_PREFIX) async def get_qf_mch (community): pass @ bp.route ("/ pay-link") Methods= ["POST"]) async def pay_link (request: Request): requires, data = ["bills", "total", "next"], request.json logger.info (f "{request.url =}) {request.json =} ") # the corresponding order has been generated within 1 minute Pay content = request.body + f "{datetime.now ():% y%m%d%H%M%S}" .encode () body= md5 (content) .hexdigest () if not (order: = await Order.filter (body=body) .first ()): order = await new_pay_order (origin, data, request, body) mchid Mch_name = await get_qf_mch (order.community) if mchid: host = get_host (request.headers) if not UserAgent (request=request). Is_wechat: # so determine whether you are in Wechat or not If not, generate the QR code frontend_url = data ["next"] fpath = "payit/" + md5 (frontend_url.encode ()). Hexdigest () + ".png" if not (p: = BASE_DIR / "media" / fpath) .parent.exists (): p.parent.mkdir (parents=True) qrcode.make (frontend_url) ) .save (p) deco_image (p) img_url = host + URL_PREFIX + "/ media/" + fpath return json ({"payUrl": img_url}) return json (qf_pay_it (mchid Mch_name, order, host=host) url = WX_PAY_URL if not (request_data: = order.post_data) .get ("mch"): request_data.update (mch=1) # if payment is not configured, use 1 res = await async_http_post (url, request_data) try: res_json = res.json () except Exception as e: logger.error (f "{e =}) {url =}; {order.post_data=}; {res.content =} ") return json (res_json) Thank you for your reading, which is" how to use Python to add prompt text to QR code pictures ". After the study of this article, I believe you have a deeper understanding of how to use Python to add prompt text to QR code pictures. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report