|
import os |
|
import logging |
|
import base64 |
|
from PIL import Image |
|
import io |
|
|
|
def validate_image(image_path, max_size_mb=10): |
|
""" |
|
التحقق من صحة الصورة وتحسينها قبل إرسالها إلى API |
|
|
|
المعلمات: |
|
image_path: مسار الصورة |
|
max_size_mb: الحجم الأقصى المسموح به بالميجابايت |
|
|
|
العوائد: |
|
tuple: (صورة محسنة، نوع الملف، حالة الصلاحية، رسالة الخطأ) |
|
""" |
|
try: |
|
|
|
if not os.path.exists(image_path): |
|
return None, None, False, f"الملف غير موجود: {image_path}" |
|
|
|
|
|
file_size_mb = os.path.getsize(image_path) / (1024 * 1024) |
|
if file_size_mb > max_size_mb: |
|
return None, None, False, f"حجم الملف كبير جداً: {file_size_mb:.2f} ميجابايت (الحد الأقصى: {max_size_mb} ميجابايت)" |
|
|
|
|
|
_, ext = os.path.splitext(image_path) |
|
ext = ext.lower() |
|
|
|
if ext in ('.jpg', '.jpeg'): |
|
file_type = "image/jpeg" |
|
elif ext == '.png': |
|
file_type = "image/png" |
|
elif ext == '.gif': |
|
file_type = "image/gif" |
|
elif ext == '.webp': |
|
file_type = "image/webp" |
|
else: |
|
return None, None, False, f"نوع الملف غير مدعوم: {ext}" |
|
|
|
|
|
try: |
|
with Image.open(image_path) as img: |
|
|
|
width, height = img.size |
|
if width > 4000 or height > 4000: |
|
|
|
img = img.resize((min(width, 4000), min(height, 4000)), Image.LANCZOS) |
|
|
|
|
|
if ext == '.png' and img.mode == 'RGBA': |
|
|
|
background = Image.new('RGB', img.size, (255, 255, 255)) |
|
background.paste(img, mask=img.split()[3]) |
|
img = background |
|
|
|
|
|
buffer = io.BytesIO() |
|
img.save(buffer, format=file_type.split('/')[1].upper()) |
|
buffer.seek(0) |
|
|
|
|
|
file_content = buffer.getvalue() |
|
file_base64 = base64.b64encode(file_content).decode('utf-8') |
|
|
|
return file_base64, file_type, True, "" |
|
|
|
except Exception as e: |
|
return None, None, False, f"خطأ في معالجة الصورة: {str(e)}" |
|
|
|
except Exception as e: |
|
return None, None, False, f"خطأ في التحقق من الصورة: {str(e)}" |
|
|