Skip to content

Commit 261984c

Browse files
author
Hugo Osvaldo Barrera
committed
Add forward-compatibility with Pillow 8.0.0
1 parent 23a4388 commit 261984c

File tree

3 files changed

+43
-4
lines changed

3 files changed

+43
-4
lines changed

barcode/base.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,7 @@ def write(self, fp, options=None, text=None):
8080
Text to render under the barcode.
8181
"""
8282
output = self.render(options, text)
83-
if hasattr(output, "tostring"):
84-
output.save(fp, format=self.writer.format)
85-
else:
86-
fp.write(output)
83+
self.writer.write(output, fp)
8784

8885
def render(self, writer_options=None, text=None):
8986
"""Renders the barcode using `self.writer`.

barcode/writer.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import gzip
22
import os
33
import xml.dom
4+
from typing.io import BinaryIO
45

56
from barcode.version import version
67

@@ -318,6 +319,13 @@ def save(self, filename, output):
318319
f.write(output)
319320
return _filename
320321

322+
def write(self, content, fp: BinaryIO):
323+
"""Write `content` into a file-like object.
324+
325+
Content should be a barcode rendered by this writer.
326+
"""
327+
fp.write(content)
328+
321329

322330
if Image is None:
323331
ImageWriter = None
@@ -367,3 +375,10 @@ def save(self, filename, output):
367375
filename = "{}.{}".format(filename, self.format.lower())
368376
output.save(filename, self.format.upper())
369377
return filename
378+
379+
def write(self, content, fp: BinaryIO):
380+
"""Write `content` into a file-like object.
381+
382+
Content should be a barcode rendered by this writer.
383+
"""
384+
content.save(fp, format=self.format)

tests/test_writers.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import os
2+
from io import BytesIO
3+
4+
from barcode import EAN13
5+
from barcode.writer import ImageWriter
6+
from barcode.writer import SVGWriter
7+
8+
9+
PATH = os.path.dirname(os.path.abspath(__file__))
10+
TESTPATH = os.path.join(PATH, "test_outputs")
11+
12+
if ImageWriter:
13+
14+
def test_saving_image_to_byteio():
15+
rv = BytesIO()
16+
EAN13(str(100000902922), writer=ImageWriter()).write(rv)
17+
18+
with open(f"{TESTPATH}/somefile.jpeg", "wb") as f:
19+
EAN13("100000011111", writer=ImageWriter()).write(f)
20+
21+
22+
def test_saving_svg_to_byteio():
23+
rv = BytesIO()
24+
EAN13(str(100000902922), writer=SVGWriter()).write(rv)
25+
26+
with open(f"{TESTPATH}/somefile.svg", "wb") as f:
27+
EAN13("100000011111", writer=SVGWriter()).write(f)

0 commit comments

Comments
 (0)