You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python qrcode模块生成自定义颜色的SVG格式vCard二维码

解决Python qrcode模块生成彩色SVG二维码的问题

先处理AttributeError: module 'PIL.Image' has no attribute 'Resampling'错误

这个问题源于你的Pillow(PIL)版本低于9.1.0:

  • Pillow 9.1.0及以上版本新增了Image.Resampling枚举类,替代了旧版本的Image.LANCZOS这类常量;旧版本没有该属性。
  • 两种解决方式:
    1. 升级Pillow:执行命令 pip install --upgrade pillow
    2. 替换代码中的Resampling为对应旧常量(例如用到LANCZOS采样时,换成Image.LANCZOS)

生成彩色SVG二维码的正确方法

python-qrcode默认生成的SVG二维码为黑白,可通过以下两种方式设置自定义颜色:

方法一:自定义SvgSquareDrawer(推荐)

先确保qrcode模块为最新版本(执行pip install --upgrade qrcode),再通过SvgSquareDrawer的颜色参数生成彩色SVG:

import qrcode
from qrcode.image.svg import SvgSquareDrawer, SvgImage

# 构造vCard内容
vcard_content = """BEGIN:VCARD
VERSION:3.0
FN:张三
TEL:+8613800138000
EMAIL:zhangsan@example.com
END:VCARD"""

# 初始化二维码
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data(vcard_content)
qr.make(fit=True)

# 创建带颜色的SVG二维码
colored_svg = qr.make_image(
    image_factory=SvgImage,
    drawer=SvgSquareDrawer(fill_color="#2c3e50", background_color="#ecf0f1")
)

# 保存文件
with open("colored_vcard.svg", "wb") as f:
    colored_svg.save(f)

方法二:修改生成的SVG文本内容

如果你的qrcode版本不支持SvgSquareDrawer的颜色参数,可先生成默认黑白SVG,再替换文本中的颜色值:

import qrcode
from qrcode.image.svg import SvgImage

# 构造vCard内容(同上)
vcard_content = """BEGIN:VCARD
VERSION:3.0
FN:张三
TEL:+8613800138000
EMAIL:zhangsan@example.com
END:VCARD"""

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data(vcard_content)
qr.make(fit=True)

# 生成默认黑白SVG
svg_img = qr.make_image(image_factory=SvgImage)
# 读取SVG文本并替换颜色
svg_text = svg_img.to_string().decode("utf-8")
# 将黑色填充替换为自定义色,白色背景替换为自定义色
svg_text = svg_text.replace("#000000", "#2c3e50").replace("#ffffff", "#ecf0f1")

# 保存修改后的SVG
with open("colored_vcard.svg", "w", encoding="utf-8") as f:
    f.write(svg_text)

注意事项

你之前尝试结合StyledPilImage和SvgSquareDrawer是错误的——StyledPilImage是针对PIL位图(如PNG)的样式处理类,和SVG矢量图生成逻辑不兼容,处理SVG二维码时只需使用qrcode库中SVG相关的类即可。

内容的提问来源于stack exchange,提问作者xph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:31:30