Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eb74d35

Browse files
committed
Don't use indexed color for grayscale.
It seems to cause problems with images used for alpha transparency. It also doesn't have any benefit, since Pillow seems to always use 8-bit indexed color, even when 1-, 2-, or 4-bit indexed color is possible.
1 parent 40132e7 commit eb74d35

File tree

1 file changed

+2
-8
lines changed

1 file changed

+2
-8
lines changed

lib/matplotlib/backends/backend_pdf.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1570,7 +1570,7 @@ def _writeImg(self, data, id, smask=None):
15701570
data = data.squeeze(axis=-1)
15711571
img = Image.fromarray(data)
15721572
img_colors = img.getcolors(maxcolors=256)
1573-
if img_colors is not None:
1573+
if colors == 3 and img_colors is not None:
15741574
# Convert to indexed color if there are 256 colors or fewer
15751575
# This can significantly reduce the file size
15761576
num_colors = len(img_colors)
@@ -1580,14 +1580,8 @@ def _writeImg(self, data, id, smask=None):
15801580
if bit_depth is None or palette is None:
15811581
raise RuntimeError("invalid PNG header")
15821582
palette = palette[:num_colors * 3] # Trim padding
1583-
if colors == 1:
1584-
# The PNG format uses an RGB palette for all indexed color
1585-
# images, but the PDF format allows for grayscale palettes.
1586-
# Thus, we convert the palette.
1587-
palette = palette[::3]
15881583
palette = pdfRepr(palette)
1589-
colorspace = obj['ColorSpace'].pdfRepr()
1590-
obj['ColorSpace'] = Verbatim(b'[/Indexed ' + colorspace + b' '
1584+
obj['ColorSpace'] = Verbatim(b'[/Indexed /DeviceRGB '
15911585
+ str(num_colors - 1).encode()
15921586
+ b' ' + palette + b']')
15931587
obj['BitsPerComponent'] = bit_depth

0 commit comments

Comments
 (0)