I'm trying to use ResizedImageField instead of ImageField in Django to convert image files to .webp format. Most of the images work fine, but I'm having an issue with raw images taken by my iPhone. When I upload these raw images, they are rotated 90 degrees for some reason. However, if I edit these raw images (like cropping them), they are not rotated. I'm using django-resized version 1.0.2.
This is my models.py
class ArticleImage(models.Model):
# upload_file = models.ImageField(upload_to='article/image/%Y/%m/%d/', null=True, blank=False)
upload_file = ResizedImageField(size=None, upload_to='article/image/%Y/%m/%d/', quality=95, force_format='WEBP', null=True, blank=False)
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='image', null=True)
def delete(self, *args, **kargs):
# 데이터 삭제 시, 실제 파일도 삭제
if self.upload_file:
os.remove(os.path.join(settings.MEDIA_ROOT, self.upload_file.path))
super(ArticleImage, self).delete(*args, **kargs)
def filename(self):
return os.path.basename(self.upload_file.name)
This is my setting.py
DJANGORESIZED_DEFAULT_KEEP_META = False
DJANGORESIZED_DEFAULT_QUALITY = 95
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'WEBP'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'WEBP': ".webp"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = False
I have tried adding DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = False, but still does not work.
Try with pillow
from django.db import models
from django_resized import ResizedImageField
from PIL import Image, ExifTags
class ArticleImage(models.Model):
upload_file = ResizedImageField(
size=None,
upload_to='article/image/%Y/%m/%d/',
quality=95,
force_format='WEBP',
null=True,
blank=False
)
def save(self, *args, **kwargs):
if self.upload_file:
# Open the image using Pillow
image = Image.open(self.upload_file)
# Check for EXIF data and rotation information
if hasattr(image, '_getexif'):
exif = image._getexif()
if exif and ExifTags.TAGS.get(orientation := exif.get(0x0112)):
if orientation == 3:
image = image.rotate(180, expand=True)
elif orientation == 6:
image = image.rotate(270, expand=True)
elif orientation == 8:
image = image.rotate(90, expand=True)
# Save the modified image
image.save(self.upload_file.path, 'WEBP')
super().save(*args, **kwargs)