File: //home/arjun/projects/aigenerator/AI-LG-backend/Ai_logo_generation/utils/validators.py
from PIL import Image
from io import BytesIO
from rest_framework.exceptions import ValidationError
def validate_image_with_tolerance(image_file, aspect_ratio_tolerance=0.05):
try:
image = Image.open(BytesIO(image_file))
width, height = image.size
except Exception as e:
raise ValidationError(f"Invalid Image: {str(e)}")
if height <= width:
raise ValidationError("Image height must be greater than image width")
ratio = height / width
target_ratio = 4 / 3
lower_bound = target_ratio - aspect_ratio_tolerance
upper_bound = target_ratio + aspect_ratio_tolerance
if not (lower_bound <= ratio <= upper_bound):
raise ValidationError("Image must have a 4:3 aspect ratio")
return True
def validate_hex_color_code(value):
# Check if the hex color is valid
if not value.startswith("#") or len(value) != 7:
raise ValidationError("Hex color must start with '#' and be 7 characters long.")
if not all(c in "0123456789ABCDEFabcdef" for c in value[1:]):
raise ValidationError("Hex color must be a valid hex code.")
return value