Coverage for collectra/displays/preview.py: 100.00%

25 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Bound browser image/canvas memory independently of source resolution.""" 

2 

3from pathlib import Path 

4 

5from PIL import Image, ImageOps 

6 

7MAX_PREVIEW_EDGE = 4096 

8 

9 

10def bounded(image, *, mask=False, max_pixels=None): 

11 limit = max_pixels if max_pixels is not None else MAX_PREVIEW_EDGE 

12 if max(image.size) <= limit: 

13 return image 

14 size = tuple(max(1, round(value * limit / max(image.size))) for value in image.size) 

15 return image.resize(size, Image.Resampling.NEAREST if mask else Image.Resampling.LANCZOS) 

16 

17 

18def open_preview(path, bounds, mode, *, max_pixels=None): 

19 """Decode JPEGs at reduced resolution where the displayed crop permits it.""" 

20 limit = max_pixels if max_pixels is not None else MAX_PREVIEW_EDGE 

21 with Image.open(path) as source: 

22 # ``bounds`` are in displayed (EXIF-oriented) pixels, like every other 

23 # coordinate in Collectra, so orient before cropping. 

24 raw_width, raw_height = source.size 

25 oriented = Path(path).suffix.lower() not in {".tif", ".tiff"} 

26 turned = oriented and source.getexif().get(0x0112) in {5, 6, 7, 8} 

27 width, height = (raw_height, raw_width) if turned else (raw_width, raw_height) 

28 left, top, right, bottom = bounds 

29 scale = min(1, limit / max(right - left, bottom - top)) 

30 source.draft( 

31 mode, (max(1, round(raw_width * scale)), max(1, round(raw_height * scale))) 

32 ) 

33 source = ImageOps.exif_transpose(source) if oriented else source.copy() 

34 scaled = (left * source.width / width, top * source.height / height, 

35 right * source.width / width, bottom * source.height / height) 

36 if bounds != (0, 0, width, height): 

37 source = source.crop(tuple(round(value) for value in scaled)) 

38 source.thumbnail((limit, limit), Image.Resampling.LANCZOS) 

39 return source.convert(mode)