diff --git a/README.rst b/README.rst index 7d07b09..80785e8 100644 --- a/README.rst +++ b/README.rst @@ -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``. diff --git a/barcode/writer.py b/barcode/writer.py index 5f4b1e6..c87355b 100755 --- a/barcode/writer.py +++ b/barcode/writer.py @@ -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): diff --git a/tests/test_writers.py b/tests/test_writers.py index 2cccc02..df178b2 100644 --- a/tests/test_writers.py +++ b/tests/test_writers.py @@ -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()