diff options
author | Paul Frazee <pfrazee@gmail.com> | 2022-12-26 12:01:40 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-12-26 12:01:40 -0600 |
commit | 838fc601c1f89f028862212d169aebe4163c8672 (patch) | |
tree | e00dd942ea0b07f1560e4580c6f273a746c4808c /src/lib | |
parent | 8652b74a38f67e7f88890c9c3eb3be090b53462c (diff) | |
download | voidsky-838fc601c1f89f028862212d169aebe4163c8672.tar.zst |
Start with highest quality compression and find a suitable size (#33)
Diffstat (limited to 'src/lib')
-rw-r--r-- | src/lib/images.ts (renamed from src/lib/download.ts) | 46 |
1 files changed, 41 insertions, 5 deletions
diff --git a/src/lib/download.ts b/src/lib/images.ts index c53d809b1..caeb96d27 100644 --- a/src/lib/download.ts +++ b/src/lib/images.ts @@ -1,11 +1,13 @@ import RNFetchBlob from 'rn-fetch-blob' import ImageResizer from '@bam.tech/react-native-image-resizer' +import {Image as PickedImage} from 'react-native-image-crop-picker' export interface DownloadAndResizeOpts { uri: string width: number height: number mode: 'contain' | 'cover' | 'stretch' + maxSize: number timeout: number } @@ -41,21 +43,55 @@ export async function downloadAndResize(opts: DownloadAndResizeOpts) { localUri = `file://${localUri}` } + return await resize(localUri, opts) + } finally { + if (downloadRes) { + downloadRes.flush() + } + } +} + +export interface ResizeOpts { + width: number + height: number + mode: 'contain' | 'cover' | 'stretch' + maxSize: number +} + +export async function resize(localUri: string, opts: ResizeOpts) { + for (let i = 0; i < 9; i++) { + const quality = 1.0 - i / 10 const resizeRes = await ImageResizer.createResizedImage( localUri, opts.width, opts.height, 'JPEG', - 0.7, + quality, undefined, undefined, undefined, {mode: opts.mode}, ) - return resizeRes - } finally { - if (downloadRes) { - downloadRes.flush() + console.log(quality, resizeRes) + if (resizeRes.size < opts.maxSize) { + return resizeRes } } + throw new Error( + `This image is too big! We couldn't compress it down to ${opts.maxSize} bytes`, + ) +} + +export async function compressIfNeeded(img: PickedImage, maxSize: number) { + const origUri = `file://${img.path}` + if (img.size < maxSize) { + return origUri + } + const resizeRez = await resize(origUri, { + width: img.width, + height: img.height, + mode: 'stretch', + maxSize, + }) + return resizeRez.uri } |