pythonsvgqr-code

Style python qrcode SVG image


I use the python module "qrcode" to create vCard QR codes:

https://github.com/lincolnloop/python-qrcode

It works, but i want to create the QR code images in SVG format and style them, for example by defining the color of the QR code.

Having tried around with .png format, the linked documentation is enough information to get this done.

Now, using .svg, i can create working codes, but only black code on white background - and i can't make use of the information in the docs to specify the color.

Here's the QR code generation i use (shortened):

import qrcode
import qrcode.image.svg

vcard_data = """BEGIN:VCARD
VERSION:3.0
...etc...
END:VCARD"""

factory = qrcode.image.svg.SvgPathImage
img = qrcode.make(vcard_data, image_factory=factory)

img.save(output_image) # full path and name of the .svg defined before

When using .png, i could modify colors using

img = qr.make_image(fill_color=(12, 73, 114), back_color=(255, 255, 255))

...but the whole PNG image creation uses .make_image, while the SVG is created using .make and that doesn't take arguments like this.

How can i adjust the color settings of the resulting SVG?

Update:

I tried to generate an SVG using .make_image but i can't make that work. All styling options seem to rely on StylerdPilImage but that seems like it only supports .png.

If i understand the docs correctly, an image_factory and a module_drawer and a color_mask should work, but as far as i can tell not for SVG.

This is what i've tried now, but it does not work:

import qrcode
import qrcode.image.svg
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers.svg import SvgSquareDrawer
from qrcode.image.styles.colormasks import SolidFillColorMask
    
qr = qrcode.QRCode(
    version=None,
    error_correction=qrcode.constants.ERROR_CORRECT_M,
    box_size=4,
    border=0,
    image_factory=StyledPilImage
)

qr.add_data(vcard_data)

img = qr.make_image(
    module_drawer=SvgSquareDrawer(), 
    color_mask=SolidFillColorMask(
        front_color=(12, 73, 114),
        back_color=(255, 255, 255)
    )
)

img.save(output_image)

That leads to:

AttributeError: module 'PIL.Image' has no attribute 'Resampling'

I begin to think no one uses the "qrcode" module to generate styled SVGs. It seems like this could be done somehow, but... not really?


Solution

  • My solution right now, as i can't find a way to specify the color on creation of the .svg:

    I read the generatet image file, change the values and save it again. Not the most elegant way, but working.

    with open(output_image, "r") as qr_img:
        content = qr_img.read()
    
    content = content.replace("#000000", qr_color) # a hex color string like "#FF0000"
    
    with open(output_image, "w+") as qr_img:
        qr_img.write(content)