Skip to content

Commit

Permalink
Allow setting embedded image size in relation to the QR code width
Browse files Browse the repository at this point in the history
  • Loading branch information
lsgd committed Apr 8, 2024
1 parent b80fea6 commit 7088880
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 4 additions & 1 deletion qrcode/image/styledpil.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class StyledPilImage(qrcode.image.base.BaseImageWithDrawer):
data integrity A resampling filter can be specified (defaulting to
PIL.Image.Resampling.LANCZOS) for resizing; see PIL.Image.resize() for possible
options for this parameter.
The image size can be controlled by `embeded_image_ratio` which is a ratio
between 0 and 1 that's set in relation to the overall width of the QR code.
"""

kind = "PNG"
Expand All @@ -44,6 +46,7 @@ def __init__(self, *args, **kwargs):
self.color_mask = kwargs.get("color_mask", SolidFillColorMask())
embeded_image_path = kwargs.get("embeded_image_path", None)
self.embeded_image = kwargs.get("embeded_image", None)
self.embeded_image_ratio = kwargs.get("embeded_image_ratio", 0.25)
self.embeded_image_resample = kwargs.get(
"embeded_image_resample", Image.Resampling.LANCZOS
)
Expand Down Expand Up @@ -87,7 +90,7 @@ def draw_embeded_image(self):
return
total_width, _ = self._img.size
total_width = int(total_width)
logo_width_ish = int(total_width / 4)
logo_width_ish = int(total_width * self.embeded_image_ratio)
logo_offset = (
int((int(total_width / 2) - int(logo_width_ish / 2)) / self.box_size)
* self.box_size
Expand Down
8 changes: 8 additions & 0 deletions qrcode/tests/test_qrcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,14 @@ def test_render_styled_with_embeded_image(self):
img = qr.make_image(image_factory=StyledPilImage, embeded_image=embeded_img)
img.save(io.BytesIO())

@unittest.skipIf(not pil_Image, "Requires PIL")
def test_render_styled_with_embeded_image_and_ratio(self):
embeded_img = pil_Image.new("RGB", (10, 10), color="red")
qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
qr.add_data(UNICODE_TEXT)
img = qr.make_image(image_factory=StyledPilImage, embeded_image=embeded_img, embeded_image_ratio=0.3)
img.save(io.BytesIO())

@unittest.skipIf(not pil_Image, "Requires PIL")
def test_render_styled_with_embeded_image_path(self):
tmpfile = os.path.join(self.tmpdir, "test.png")
Expand Down

0 comments on commit 7088880

Please sign in to comment.