File size: 1,962 Bytes
912284f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import os
import requests
import base64
import hashlib
import io
from PIL import Image
from typing import List, Union
def encode_image_to_base64(image, target_size=None):
"""Encode an image to base64 string."""
if target_size is not None:
width, height = image.size
# Resize the image while maintaining the aspect ratio
if width > height:
new_width = target_size
new_height = int(height * target_size / width)
else:
new_height = target_size
new_width = int(width * target_size / height)
image = image.resize((new_width, new_height))
buffer = io.BytesIO()
image.save(buffer, format="JPEG")
return base64.b64encode(buffer.getvalue()).decode('utf-8')
def decode_base64_to_image(base64_string):
"""Decode a base64 string to an image."""
image_data = base64.b64decode(base64_string)
return Image.open(io.BytesIO(image_data))
def decode_base64_to_image_file(base64_string, output_path):
"""Decode a base64 string and save it to a file."""
image = decode_base64_to_image(base64_string)
image.save(output_path)
def download_file(url, local_path):
"""Download a file from a URL to a local path."""
response = requests.get(url, stream=True)
response.raise_for_status()
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
def md5(file_path):
"""Calculate the MD5 hash of a file."""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def toliststr(s):
if isinstance(s, str) and (s[0] == '[') and (s[-1] == ']'):
return [str(x) for x in eval(s)]
elif isinstance(s, str):
return [s]
elif isinstance(s, list):
return [str(x) for x in s]
raise NotImplementedError
|