|
23 | 23 | SOURCE_NAME:str = 'Source'
|
24 | 24 | chapter_prefix:str = 'v' # :) :D C:
|
25 | 25 |
|
| 26 | +def get_size_that_preserves_ratio(*, img_size, size_of_viewport): |
| 27 | + # derived from https://pillow.readthedocs.io/en/stable/_modules/PIL/Image.html#Image.thumbnail (HPND) |
| 28 | + import math |
| 29 | + def round_aspect(number, key): |
| 30 | + return max(min(math.floor(number), math.ceil(number), key=key), 1) |
| 31 | + |
| 32 | + x, y = size_of_viewport |
| 33 | + |
| 34 | + width, height = img_size |
| 35 | + |
| 36 | + aspect = width / height |
| 37 | + if x / y >= aspect: |
| 38 | + x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) |
| 39 | + else: |
| 40 | + y = round_aspect( |
| 41 | + x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) |
| 42 | + ) |
| 43 | + return x, y |
| 44 | + |
26 | 45 |
|
27 | 46 | def write_zip(savepath, chapters):
|
28 | 47 | new_zip = ZipFile(savepath,'w')
|
@@ -128,13 +147,18 @@ def convert_page_worker(source, options, savedir=None):
|
128 | 147 | if page.landscape:
|
129 | 148 | new_size = new_size[::-1]
|
130 | 149 | n_width, n_height = new_size
|
| 150 | + if options['keep_ratio']: |
| 151 | + resize_size = get_size_that_preserves_ratio(img_size=(width, height), size_of_viewport=new_size) |
| 152 | + log_buff += f'|trans: keeping ratio: size changed from {(width, height)} to {resize_size}\n' |
| 153 | + else: |
| 154 | + resize_size = new_size |
131 | 155 | # downscaling
|
132 | 156 | if (width > n_width and height > n_height
|
133 | 157 | and not options['nodown']):
|
134 |
| - img = img.resize((new_size), config.RESAMPLE_TYPE) |
| 158 | + img = img.resize(resize_size, config.RESAMPLE_TYPE) |
135 | 159 | # upscaling
|
136 | 160 | elif not options['noup']:
|
137 |
| - img = img.resize((new_size), config.RESAMPLE_TYPE) |
| 161 | + img = img.resize(resize_size, config.RESAMPLE_TYPE) |
138 | 162 |
|
139 | 163 | LossyFmt.quality = options['quality']
|
140 | 164 |
|
@@ -248,6 +272,7 @@ def __init__(self, filename:str):
|
248 | 272 | self._page_opt['format'] = get_format_class(config.img_format)
|
249 | 273 | self._page_opt['quality'] = config.img_quality
|
250 | 274 | self._page_opt['size'] = config.img_size
|
| 275 | + self._page_opt['keep_ratio'] = config.keep_ratio |
251 | 276 | self._page_opt['grayscale'] = config.grayscale
|
252 | 277 | self._page_opt['noup'] = config.no_upscale
|
253 | 278 | self._page_opt['nodown'] = config.no_downscale
|
|
0 commit comments