Skip to content

Commit 2ddbc55

Browse files
committed
Allow png factory to save to a string path
Fixes #306
1 parent 8d38c15 commit 2ddbc55

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

CHANGES.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ Change log
55
7.5 (unreleased)
66
================
77

8-
- Nothing changed yet.
8+
- Allow ``pypng`` factory to allow for saving to a string (like
9+
``qr.save("some_file.png")``) in addition to file-like objects.
910

1011

1112
7.4.1 (3 February 2023)

qrcode/image/pure.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ def drawrect(self, row, col):
2323
"""
2424

2525
def save(self, stream, kind=None):
26+
if isinstance(stream, str):
27+
stream = open(stream, "wb")
2628
self._img.write(stream, self.rows_iter())
2729

2830
def rows_iter(self):

qrcode/tests/test_qrcode.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,18 @@ def test_render_pypng(self):
184184
print(img.width, img.box_size, img.border)
185185
img.save(io.BytesIO())
186186

187+
def test_render_pypng_to_str(self):
188+
qr = qrcode.QRCode()
189+
qr.add_data(UNICODE_TEXT)
190+
img = qr.make_image(image_factory=PyPNGImage)
191+
self.assertIsInstance(img.get_image(), png.Writer)
192+
193+
mock_open = mock.mock_open()
194+
with mock.patch("qrcode.image.pure.open", mock_open, create=True):
195+
img.save("test_file.png")
196+
mock_open.assert_called_once_with("test_file.png", "wb")
197+
mock_open("test_file.png", "wb").write.assert_called()
198+
187199
@unittest.skipIf(not pil_Image, "Requires PIL")
188200
def test_render_styled_Image(self):
189201
qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)

0 commit comments

Comments
 (0)