Files
dj_beyhan/core/utils/utils.py
Beyhan Oğur 3de0ca1fb5 first commit
2026-04-26 22:23:47 +03:00

41 lines
1.1 KiB
Python

import os
import uuid
from django.utils.deconstruct import deconstructible
from imagekit.processors import ResizeToFill
class ConvertToRGBA(object):
"""Converts an image to RGBA mode."""
def process(self, img):
if img.mode not in ('RGBA', 'LA'):
img = img.convert('RGBA')
return img
@deconstructible
class UniquePathAndRename(object):
def __init__(self, upload_to):
self.upload_to = upload_to
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
new_filename = f"{uuid.uuid4().hex}.{ext}"
return os.path.join(self.upload_to, new_filename)
def image_optimizer(upload_to, width, height, quality, img_format):
"""
ProcessedImageField için gerekli olan `upload_to`, `processors`, `format`
ve `options` parametrelerini dinamik olarak oluşturur.
"""
processors = [ResizeToFill(width, height)]
if img_format == 'PNG':
processors.insert(0, ConvertToRGBA())
return {
'upload_to': UniquePathAndRename(upload_to),
'processors': processors,
'format': img_format,
'options': {'quality': quality}
}