Skip to content

Commit d44a409

Browse files
authored
Merge pull request #360 from lsgd/main
Allow setting embedded image size in relation to the QR code width
2 parents b80fea6 + 7088880 commit d44a409

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

qrcode/image/styledpil.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ class StyledPilImage(qrcode.image.base.BaseImageWithDrawer):
3232
data integrity A resampling filter can be specified (defaulting to
3333
PIL.Image.Resampling.LANCZOS) for resizing; see PIL.Image.resize() for possible
3434
options for this parameter.
35+
The image size can be controlled by `embeded_image_ratio` which is a ratio
36+
between 0 and 1 that's set in relation to the overall width of the QR code.
3537
"""
3638

3739
kind = "PNG"
@@ -44,6 +46,7 @@ def __init__(self, *args, **kwargs):
4446
self.color_mask = kwargs.get("color_mask", SolidFillColorMask())
4547
embeded_image_path = kwargs.get("embeded_image_path", None)
4648
self.embeded_image = kwargs.get("embeded_image", None)
49+
self.embeded_image_ratio = kwargs.get("embeded_image_ratio", 0.25)
4750
self.embeded_image_resample = kwargs.get(
4851
"embeded_image_resample", Image.Resampling.LANCZOS
4952
)
@@ -87,7 +90,7 @@ def draw_embeded_image(self):
8790
return
8891
total_width, _ = self._img.size
8992
total_width = int(total_width)
90-
logo_width_ish = int(total_width / 4)
93+
logo_width_ish = int(total_width * self.embeded_image_ratio)
9194
logo_offset = (
9295
int((int(total_width / 2) - int(logo_width_ish / 2)) / self.box_size)
9396
* self.box_size

qrcode/tests/test_qrcode.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,14 @@ def test_render_styled_with_embeded_image(self):
211211
img = qr.make_image(image_factory=StyledPilImage, embeded_image=embeded_img)
212212
img.save(io.BytesIO())
213213

214+
@unittest.skipIf(not pil_Image, "Requires PIL")
215+
def test_render_styled_with_embeded_image_and_ratio(self):
216+
embeded_img = pil_Image.new("RGB", (10, 10), color="red")
217+
qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
218+
qr.add_data(UNICODE_TEXT)
219+
img = qr.make_image(image_factory=StyledPilImage, embeded_image=embeded_img, embeded_image_ratio=0.3)
220+
img.save(io.BytesIO())
221+
214222
@unittest.skipIf(not pil_Image, "Requires PIL")
215223
def test_render_styled_with_embeded_image_path(self):
216224
tmpfile = os.path.join(self.tmpdir, "test.png")

0 commit comments

Comments
 (0)