44from django .db import migrations
55import requests
66import webp
7+ from typing import Optional
78
89from PIL import Image
910
1011from files .service import SelectelSwiftStorage
1112
1213
13- def convert_image_to_webp (pil_image : Image , quality : int ) -> bytes :
14- config = webp .WebPConfig .new (preset = webp .WebPPreset .PHOTO , quality = quality )
15- webp_image = webp .WebPPicture .from_pil (pil_image )
16- return webp_image .encode (config )
14+ def convert_image_to_webp (pil_image : Image , quality : int ) -> Optional [BytesIO ]:
15+ """
16+ Convert a PIL Image to WebP format.
17+
18+ Parameters:
19+ - pil_image (PIL.Image): A PIL Image object to be converted.
20+ - quality (int): The quality of the converted WebP image, 0 to 100.
21+
22+ Returns:
23+ - bytes: The converted WebP image in bytes, or None if the conversion fails.
24+ """
25+ try :
26+ config = webp .WebPConfig .new (preset = webp .WebPPreset .PHOTO , quality = quality )
27+ webp_data = webp .WebPPicture .from_pil (pil_image ).encode (config = config )
28+ return BytesIO (webp_data .buffer ())
29+ except Exception as e :
30+ print (f"An error occurred: { e } " )
31+ return None
1732
1833
1934def migration (apps , schema_editor ):
@@ -31,6 +46,7 @@ def migration(apps, schema_editor):
3146 pil_image .thumbnail ((512 , 512 ), Image .ANTIALIAS )
3247 # convert image to webp
3348 webp_file = convert_image_to_webp (pil_image , quality = 80 )
49+ # delete old file
3450 storage .delete (i .link )
3551
3652 new_url = str (i .link ).rsplit ("." , 1 )[0 ] + ".webp"
@@ -41,11 +57,11 @@ def migration(apps, schema_editor):
4157 "X-Auth-Token" : token ,
4258 "Content-Type" : "image/webp" ,
4359 },
44- data = webp_file . __bytes__ ,
60+ data = webp_file ,
4561 )
4662 i .link = new_url
47- i .extension = ' webp'
48- i .mime_type = ' image/webp'
63+ i .extension = " webp"
64+ i .mime_type = " image/webp"
4965 i .save ()
5066
5167
0 commit comments