from PIL import Image
import base64
import io
import os
from IPython.display import IFrame, SVG, display#, Image
!du -sh *
#https://stackoverflow.com/questions/48229318/how-to-convert-image-pil-into-base64-without-saving/48229407 #by @Taha Mahjoubi
def img_to_base64_str(img):
buffered = io.BytesIO()
img.save(buffered, format="PNG")
buffered.seek(0)
img_byte = buffered.getvalue()
img_str = "data:image/png;base64," + base64.b64encode(img_byte).decode()
return img_str
def img_from_base64_str(msg):
msg = msg.replace("data:image/png;base64,", "")
msg = base64.b64decode(msg)
buf = io.BytesIO(msg)
img = Image.open(buf)
return img
cols = 5
padding = 100
images = [
*[f"./images2/{filename}" for filename in os.listdir("./images2/")]
]
size = 0
rowheight = {-1:0}
x = padding
y = padding
svgimages = []
for image in images:
if '.ipynb_checkpoints' in image: continue
img = Image.open(image)
b64 = img_to_base64_str(img)
rowid = int(size/cols)
#print(rowid, size%cols)
y = sum([rowheight[i] for i in range(rowid)])
if size%cols == 0:
x = padding
rowheight[rowid] = max(rowheight.get(rowid, 0), img.height+padding)
if 1:
print(image, img.width, img.height, x, y)
svgimages.append(f"""
<image x="{x}" y="{y}" href="{b64}"/>
""")
#print(x,y)
x += img.width + padding
size += 1
with open('file2.svg', 'w') as f:
imgs = "\n".join(svgimages)
f.write(f"""
<svg
xmlns="http://www.w3.org/2000/svg">
{imgs}
</svg>
""")
img = Image.open("./images/Slide1.JPG")
img.width
img.height
b64 = img_to_base64_str(img)
with open('file.svg', 'w') as f:
f.write(f"""
<svg
xmlns="http://www.w3.org/2000/svg">
<image x="200" y="200" href="{b64}"/>
</svg>
""")
Image("./24nov21-1.PNG")
base64.encode(img)