in google/generativeai/types/content_types.py [0:0]
def _pil_to_blob(image: PIL.Image.Image) -> protos.Blob:
# If the image is a local file, return a file-based blob without any modification.
# Otherwise, return a lossless WebP blob (same quality with optimized size).
def file_blob(image: PIL.Image.Image) -> protos.Blob | None:
if not isinstance(image, PIL.ImageFile.ImageFile) or image.filename is None:
return None
filename = str(image.filename)
if not pathlib.Path(filename).is_file():
return None
mime_type = image.get_format_mimetype()
image_bytes = pathlib.Path(filename).read_bytes()
return protos.Blob(mime_type=mime_type, data=image_bytes)
def webp_blob(image: PIL.Image.Image) -> protos.Blob:
# Reference: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp
image_io = io.BytesIO()
image.save(image_io, format="webp", lossless=True)
image_io.seek(0)
mime_type = "image/webp"
image_bytes = image_io.read()
return protos.Blob(mime_type=mime_type, data=image_bytes)
return file_blob(image) or webp_blob(image)