Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting embedded image size in relation to the QR code width #360

Merged
merged 1 commit into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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