Skip to content

Commit

Permalink
explore embedding base64 png images
Browse files Browse the repository at this point in the history
  • Loading branch information
relleums committed Mar 10, 2024
1 parent f46620b commit acc1e15
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 1 deletion.
2 changes: 2 additions & 0 deletions svg_cartesian_plot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
from .base import ax_add_path
from .base import ax_add_text
from .base import fig_write
from .base import ax_add_pcolormesh
from . import optics
from . import shapes
from . import hemisphere
from . import svgcartesian
from . import color
from . import text
from . import image
52 changes: 52 additions & 0 deletions svg_cartesian_plot/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
from . import svgcartesian
from . import scaling
from . import image


def Fig(cols=1920, rows=1080):
Expand Down Expand Up @@ -91,3 +92,54 @@ def ax_add_text(ax, xy=[0, 0], r=0.0, **kwargs):
def fig_write(fig, path):
dwg = fig["dwg"]
svgcartesian.write(dwg=fig["dwg"], path=path)


def ax_add_pcolormesh(ax, z, colormap, x_bin_edges=None, y_bin_edges=None, **kwargs):

"""
(x0, y1) (x1, y1)
+-----------+
| |
| |
| |
| |
+-----------+
(x0, y0) (x1, y0)
"""

z = np.asarray(z)
num_x = z.shape[0]
num_y = z.shape[1]

if x_bin_edges is None:
x_bin_edges = np.arange(0, num_x + 1)

if y_bin_edges is None:
y_bin_edges = np.arange(0, num_y + 1)

mat = np.zeros(shape=(num_x, num_y, 3), dtype=np.uint8)

for xbin in range(num_x):
for ybin in range(num_y):
mat[xbin, num_y - ybin - 1] = colormap(z[xbin, ybin])

mat64_str = image.image_to_png_base64(mat=mat)

fig = ax["fig"]
dwg = fig["dwg"]

start_xy = _ax2dwg([0, 0], fig=fig, ax=ax)
stop_xy = _ax2dwg([1, 1], fig=fig, ax=ax)

range_x = stop_xy[0] - start_xy[0]
range_y = stop_xy[1] - start_xy[1]

dwg.add(
dwg.image(
href="data:image/png;base64," + mat64_str,
width="{:f}".format(range_x),
height="{:f}".format(range_y),
x="{:f}".format(start_xy[0]),
y="{:f}".format(start_xy[1] - fig["fig"]["rows"]),
)
)
16 changes: 16 additions & 0 deletions svg_cartesian_plot/image/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from PIL import Image as pimg
import tempfile
import os
import base64

def image_to_png_base64(mat):
assert len(mat.shape) == 3
assert mat.shape[2] == 3
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "img.png")
img = pimg.fromarray(mat)
img.save(path, "PNG")
with open(path, "rb") as f:
img_bytes = f.read()
img_base64 = base64.encodebytes(img_bytes)
return str(img_base64, "ascii")
2 changes: 1 addition & 1 deletion svg_cartesian_plot/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.0.8"
__version__ = "0.0.9"

0 comments on commit acc1e15

Please sign in to comment.