from PIL import Image
import base64
import io
def image_to_base64(image_path):
with Image.open(image_path) as img:
if img.mode != 'RGB':
img = img.convert('RGB')
buffered = io.BytesIO()
img.save(buffered, format="JPEG") # or "PNG" depending on the original image format
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return img_str
def base64_to_image(base64_str, output_pth):
img_data = base64.b64decode(base64_str)
with open(output_pth, 'wb') as f:
f.write(img_data)