Skip to content

Commit

Permalink
Merge pull request #16 from not-lain/update-base64-implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
not-lain authored Jan 14, 2025
2 parents d147628 + 3ee8c4f commit 6e681b8
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/loadimg/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,14 @@ def _convert_to_output_type(
elif output_type == "numpy":
return np.array(img)
elif output_type == "base64":
buffered = BytesIO()
img.save(buffered, format=img.format or "PNG")
return base64.b64encode(buffered.getvalue()).decode()
# buffered = BytesIO()
# img.save(buffered, format=img.format or "PNG")
# return base64.b64encode(buffered.getvalue()).decode()
img_type = img.format or "PNG"
with BytesIO() as buffer:
img.save(buffer, format=img_type)
img_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
return f"data:image/{img_type.lower()};base64,{img_str}"
elif output_type == "str":
# Save to temporary file with original extension if available
ext = Path(original_name).suffix if original_name else ".png"
Expand Down Expand Up @@ -215,9 +220,10 @@ def load(
input_type = self._determine_input_type(img)

if input_type == "base64":
return self._load_from_base64_cached(
img if isinstance(img, str) else bytes(img)
)
img = re.sub(r"^data:image\/[a-zA-Z]+;base64,", "", img)
image_bytes = base64.b64decode(img)
image_file = BytesIO(image_bytes)
return Image.open(image_file), None
elif input_type == "file":
return self._load_from_file_cached(str(img))
elif input_type == "url":
Expand Down

0 comments on commit 6e681b8

Please sign in to comment.