diff options
Diffstat (limited to 'src/state/gallery.ts')
-rw-r--r-- | src/state/gallery.ts | 29 |
1 files changed, 20 insertions, 9 deletions
diff --git a/src/state/gallery.ts b/src/state/gallery.ts index f4c8b712e..55d08785e 100644 --- a/src/state/gallery.ts +++ b/src/state/gallery.ts @@ -13,7 +13,7 @@ import { import {nanoid} from 'nanoid/non-secure' import {POST_IMG_MAX} from '#/lib/constants' -import {getImageDim} from '#/lib/media/manip' +import {getImageDim, safeDeleteAsync} from '#/lib/media/manip' import {openCropper} from '#/lib/media/picker' import {getDataUriSize} from '#/lib/media/util' import {isIOS, isNative} from '#/platform/detection' @@ -212,15 +212,20 @@ export async function compressImage(img: ComposerImage): Promise<ImageMeta> { const [w, h] = containImageRes(source.width, source.height, POST_IMG_MAX) const cacheDir = isNative && getImageCacheDirectory() - for (let i = 10; i > 0; i--) { - // Float precision - const factor = i / 10 + let minQualityPercentage = 0 + let maxQualityPercentage = 101 // exclusive + let newDataUri + + while (maxQualityPercentage - minQualityPercentage > 1) { + const qualityPercentage = Math.round( + (maxQualityPercentage + minQualityPercentage) / 2, + ) const res = await manipulateAsync( source.path, [{resize: {width: w, height: h}}], { - compress: factor, + compress: qualityPercentage / 100, format: SaveFormat.JPEG, base64: true, }, @@ -229,17 +234,23 @@ export async function compressImage(img: ComposerImage): Promise<ImageMeta> { const base64 = res.base64 if (base64 !== undefined && getDataUriSize(base64) <= POST_IMG_MAX.size) { - return { + minQualityPercentage = qualityPercentage + newDataUri = { path: await moveIfNecessary(res.uri), width: res.width, height: res.height, mime: 'image/jpeg', } + } else { + maxQualityPercentage = qualityPercentage + if (cacheDir) { + await safeDeleteAsync(res.uri) + } } + } - if (cacheDir) { - await deleteAsync(res.uri) - } + if (newDataUri) { + return newDataUri } throw new Error(`Unable to compress image`) |