Bluesky app fork with some witchin' additions 💫
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add resolution downsizing to image compression (#10117)

authored by

Eric Bailey and committed by
GitHub
3e37696d 6a15ca88

+24 -13
+24 -13
src/state/gallery.ts
··· 207 207 }, 208 208 ): Promise<PickerImage> { 209 209 const source = img.transformed || img.source 210 + const highResolution = options?.highResolution ?? false 210 211 211 - const [w, h] = containImageRes( 212 - source.width, 213 - source.height, 214 - options?.highResolution 215 - ? { 216 - width: 4000, 217 - height: 4000, 218 - } 219 - : POST_IMG_MAX, 220 - ) 212 + let attempts = 0 213 + let maxDimension = highResolution ? 4000 : POST_IMG_MAX.width 221 214 222 215 let minQualityPercentage = 0 223 216 let maxQualityPercentage = 101 // exclusive 224 217 let newDataUri 225 218 226 219 while (maxQualityPercentage - minQualityPercentage > 1) { 220 + if (attempts >= 4) break 221 + 222 + const [w, h] = containImageRes(source.width, source.height, maxDimension) 227 223 const qualityPercentage = Math.round( 228 224 (maxQualityPercentage + minQualityPercentage) / 2, 229 225 ) 226 + 227 + /* 228 + * In the event the image doesn't compress well, we want to avoid 229 + * unecessary iterations. In this case, binary search will check 51, 26, 230 + * 13(rounded). We don't want to go below 25, so if we've halved to 13, 231 + * reset the loop and reduce the image dimensions instead. 232 + */ 233 + if (qualityPercentage <= 13) { 234 + minQualityPercentage = 0 235 + maxQualityPercentage = 101 236 + attempts++ 237 + // 4000px → 3200px → 2560px → 2048px → ~1638px 238 + maxDimension = Math.floor(maxDimension * 0.8) 239 + continue 240 + } 230 241 231 242 const res = await manipulateAsync( 232 243 source.path, ··· 366 377 function containImageRes( 367 378 w: number, 368 379 h: number, 369 - {width: maxW, height: maxH}: {width: number; height: number}, 380 + max: number, 370 381 ): [width: number, height: number] { 371 382 let scale = 1 372 383 373 - if (w > maxW || h > maxH) { 374 - scale = w > h ? maxW / w : maxH / h 384 + if (w > max || h > max) { 385 + scale = w > h ? max / w : max / h 375 386 w = Math.floor(w * scale) 376 387 h = Math.floor(h * scale) 377 388 }