Add: blur hash utils function
This commit is contained in:
parent
d4f08aa8b2
commit
e67f5f2dd7
1 changed files with 35 additions and 0 deletions
|
@ -1,6 +1,10 @@
|
|||
from blake3 import blake3
|
||||
from blurhash import encode
|
||||
|
||||
from tqdm.auto import tqdm
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def compute_blake3_hash(data, is_file=False, logger=None):
|
||||
"""
|
||||
|
@ -45,3 +49,34 @@ def compute_file_hash_blake3(file_path, logger=None):
|
|||
|
||||
def compute_string_hash_blake3(string, logger=None):
|
||||
return compute_blake3_hash(string, is_file=False, logger=logger)
|
||||
|
||||
|
||||
def compute_blur_hash(image_path, components_x=4, components_y=4, logger=None):
|
||||
"""
|
||||
Compute the BlurHash of an image.
|
||||
|
||||
Args:
|
||||
image_path (str): Path to the image file.
|
||||
components_x (int): Number of horizontal components for BlurHash.
|
||||
components_y (int): Number of vertical components for BlurHash.
|
||||
logger: Optional logger for error messages.
|
||||
|
||||
Returns:
|
||||
str: BlurHash string or None if an error occurs.
|
||||
"""
|
||||
try:
|
||||
with Image.open(image_path) as img:
|
||||
img = img.convert("RGB") # Ensure it's in RGB mode
|
||||
blur_hash = encode(img, components_x, components_y)
|
||||
return blur_hash
|
||||
|
||||
except Exception as e:
|
||||
error_message = f"Error computing BlurHash: {e}"
|
||||
|
||||
if logger:
|
||||
if hasattr(logger, "style") and hasattr(logger, "stdout"): # Django command
|
||||
logger.stdout.write(logger.style.WARNING(error_message))
|
||||
else: # Default to tqdm
|
||||
tqdm.write(error_message)
|
||||
|
||||
return None
|
||||
|
|
Loading…
Add table
Reference in a new issue