Skip to content

Commit

Permalink
Add support for transparent backgrounds
Browse files Browse the repository at this point in the history
Fixes #64
  • Loading branch information
Hugo Osvaldo Barrera committed Aug 15, 2020
1 parent 60ec8b1 commit 7bcb56c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
8 changes: 7 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,16 @@ Commandline::
Changelog
---------

v0.13.0
~~~~~~~

* Added support for transparent backgrounds. This is done by setting the ``mode`` option
for a writer to ``RGBA``.

v0.12.0
~~~~~~~

* Removed `writer_options` from `barcode.get`. This parameter was not used.
* Removed ``writer_options`` from ``barcode.get``. This parameter was not used.
* Add a ``with_doctype`` flag to ``SVGWriter``. Set this to false to avoid including a
``DOCTYPE`` in the resulting SVG.
* Add support for ``Pillow>=8.0.0``.
Expand Down
18 changes: 15 additions & 3 deletions barcode/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,18 +332,30 @@ def write(self, content, fp: BinaryIO):
else:

class ImageWriter(BaseWriter): # type: ignore
def __init__(self):
format: str
mode: str
dpi: int

def __init__(self, format="PNG", mode="RGB"):
"""Initialise a new write instance.
:params format: The file format for the generated image. This parameter can
take any value that Pillow accepts.
:params mode: The colour-mode for the generated image. Set this to RGBA if
you wish to use colours with transparency.
"""
BaseWriter.__init__(
self, self._init, self._paint_module, self._paint_text, self._finish
)
self.format = "PNG"
self.format = format
self.mode = mode
self.dpi = 300
self._image = None
self._draw = None

def _init(self, code):
size = self.calculate_size(len(code[0]), len(code), self.dpi)
self._image = Image.new("RGB", size, self.background)
self._image = Image.new(self.mode, size, self.background)
self._draw = ImageDraw.Draw(self._image)

def _paint_module(self, xpos, ypos, width, color):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ def test_saving_image_to_byteio():
with open(f"{TESTPATH}/somefile.jpeg", "wb") as f:
EAN13("100000011111", writer=ImageWriter()).write(f)

def test_saving_rgba_image():
rv = BytesIO()
EAN13(str(100000902922), writer=ImageWriter()).write(rv)

with open(f"{TESTPATH}/ean13-with-transparent-bg.png", "wb") as f:
writer = ImageWriter(mode="RGBA")

EAN13("100000011111", writer=writer).write(
f, options={"background": "rgba(255,0,0,0)"}
)


def test_saving_svg_to_byteio():
rv = BytesIO()
Expand Down

0 comments on commit 7bcb56c

Please sign in to comment.