|
65 | 65 | .. _xkcd color survey: https://xkcd.com/color/rgb/ |
66 | 66 | """ |
67 | 67 |
|
| 68 | +import base64 |
68 | 69 | from collections.abc import Sized |
69 | 70 | import functools |
| 71 | +import io |
70 | 72 | import itertools |
71 | 73 | from numbers import Number |
72 | 74 | import re |
| 75 | +from PIL import Image |
| 76 | +from PIL.PngImagePlugin import PngInfo |
73 | 77 |
|
| 78 | +import matplotlib as mpl |
74 | 79 | import numpy as np |
75 | 80 | import matplotlib.cbook as cbook |
76 | 81 | from matplotlib import docstring |
@@ -691,6 +696,33 @@ def reversed(self, name=None): |
691 | 696 | """ |
692 | 697 | raise NotImplementedError() |
693 | 698 |
|
| 699 | + def _repr_png_(self): |
| 700 | + """Generate a PNG representation of the Colormap.""" |
| 701 | + IMAGE_SIZE = (400, 50) |
| 702 | + X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1)) |
| 703 | + pixels = self(X, bytes=True) |
| 704 | + png_bytes = io.BytesIO() |
| 705 | + title = self.name + ' color map' |
| 706 | + author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org' |
| 707 | + pnginfo = PngInfo() |
| 708 | + pnginfo.add_text('Title', title) |
| 709 | + pnginfo.add_text('Description', title) |
| 710 | + pnginfo.add_text('Author', author) |
| 711 | + pnginfo.add_text('Software', author) |
| 712 | + Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo) |
| 713 | + return png_bytes.getvalue() |
| 714 | + |
| 715 | + def _repr_html_(self): |
| 716 | + """Generate an HTML representation of the Colormap.""" |
| 717 | + png_bytes = self._repr_png_() |
| 718 | + png_base64 = base64.b64encode(png_bytes).decode('ascii') |
| 719 | + return ('<strong>' + self.name + '</strong>' + |
| 720 | + '<img ' + |
| 721 | + 'alt="' + self.name + ' color map" ' + |
| 722 | + 'title="' + self.name + '"' + |
| 723 | + 'style="border: 1px solid #555;" ' + |
| 724 | + 'src="data:image/png;base64,' + png_base64 + '">') |
| 725 | + |
694 | 726 |
|
695 | 727 | class LinearSegmentedColormap(Colormap): |
696 | 728 | """ |
|
0 commit comments