Coverage for cookbook/helper/image_processing.py: 19%

36 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2023-12-29 00:47 +0100

1import os 

2from io import BytesIO 

3 

4from PIL import Image 

5 

6 

7def rescale_image_jpeg(image_object, base_width=1020): 

8 img = Image.open(image_object) 

9 icc_profile = img.info.get('icc_profile') # remember color profile to not mess up colors 

10 width_percent = (base_width / float(img.size[0])) 

11 height = int((float(img.size[1]) * float(width_percent))) 

12 

13 img = img.resize((base_width, height), Image.LANCZOS) 

14 img_bytes = BytesIO() 

15 img.save(img_bytes, 'JPEG', quality=90, optimize=True, icc_profile=icc_profile) 

16 

17 return img_bytes 

18 

19 

20def rescale_image_png(image_object, base_width=1020): 

21 image_object = Image.open(image_object) 

22 wpercent = (base_width / float(image_object.size[0])) 

23 hsize = int((float(image_object.size[1]) * float(wpercent))) 

24 img = image_object.resize((base_width, hsize), Image.LANCZOS) 

25 

26 im_io = BytesIO() 

27 img.save(im_io, 'PNG', quality=90) 

28 return im_io 

29 

30 

31def get_filetype(name): 

32 try: 

33 return os.path.splitext(name)[1] 

34 except Exception: 

35 return '.jpeg' 

36 

37 

38# TODO this whole file needs proper documentation, refactoring, and testing 

39# TODO also add env variable to define which images sizes should be compressed 

40# filetype argument can not be optional, otherwise this function will treat all images as if they were a jpeg 

41# Because it's no longer optional, no reason to return it 

42def handle_image(request, image_object, filetype): 

43 try: 

44 Image.open(image_object).verify() 

45 except Exception: 

46 return None 

47 

48 if (image_object.size / 1000) > 500: # if larger than 500 kb compress 

49 if filetype == '.jpeg' or filetype == '.jpg': 

50 return rescale_image_jpeg(image_object) 

51 if filetype == '.png': 

52 return rescale_image_png(image_object) 

53 return image_object