Parameterize image max dimension and blob size

Replace the hardcoded POST_IMG_MAX limits baked into the resize helpers
with explicit per-caller maxDimension/maxBytes parameters. Pasted image
URLs now pre-shrink at the high-res 4000px/2MB post limits instead of
2000px/1MB, removing a quality bottleneck before compressImage runs.
Avatar/banner/onboarding and link thumbnails keep their 2000px/1MB
limits.

Also bring web doResize to parity with native by clamping dimensions via
a shared getResizedDimensions (hoisted into media/util.ts), and shadow
the mutated maxDimension param in compressImage as a local.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Eric Bailey
2026-06-02 11:25:21 -05:00
parent 61e10f7e0b
commit e14d559a13
8 changed files with 97 additions and 74 deletions
+6 -8
View File
@@ -4,8 +4,8 @@ import {manipulateAsync, SaveFormat} from 'expo-image-manipulator'
import { import {
downloadAndResize, downloadAndResize,
type DownloadAndResizeOpts, type DownloadAndResizeOpts,
getResizedDimensions,
} from '../../src/lib/media/manip' } from '../../src/lib/media/manip'
import {getResizedDimensions} from '../../src/lib/media/util'
const mockResizedImage = { const mockResizedImage = {
path: 'file://resized-image.jpg', path: 'file://resized-image.jpg',
@@ -41,10 +41,8 @@ describe('downloadAndResize', () => {
const opts: DownloadAndResizeOpts = { const opts: DownloadAndResizeOpts = {
uri: 'https://example.com/image.jpg', uri: 'https://example.com/image.jpg',
width: 100, maxDimension: 2000,
height: 100,
maxSize: 500000, maxSize: 500000,
mode: 'cover',
timeout: 10000, timeout: 10000,
} }
@@ -60,9 +58,11 @@ describe('downloadAndResize', () => {
// First time it gets called is to get dimensions // First time it gets called is to get dimensions
expect(manipulateAsync).toHaveBeenCalledWith(expect.any(String), [], {}) expect(manipulateAsync).toHaveBeenCalledWith(expect.any(String), [], {})
// The mocked source image is 100x100, below maxDimension, so it is not
// downsized.
expect(manipulateAsync).toHaveBeenCalledWith( expect(manipulateAsync).toHaveBeenCalledWith(
expect.any(String), expect.any(String),
[{resize: {height: opts.height, width: opts.width}}], [{resize: {height: 100, width: 100}}],
{format: SaveFormat.JPEG, compress: 1.0}, {format: SaveFormat.JPEG, compress: 1.0},
) )
expect(deleteAsync).toHaveBeenCalledWith(expect.any(String), { expect(deleteAsync).toHaveBeenCalledWith(expect.any(String), {
@@ -73,10 +73,8 @@ describe('downloadAndResize', () => {
it('should return undefined for invalid URI', async () => { it('should return undefined for invalid URI', async () => {
const opts: DownloadAndResizeOpts = { const opts: DownloadAndResizeOpts = {
uri: 'invalid-uri', uri: 'invalid-uri',
width: 100, maxDimension: 2000,
height: 100,
maxSize: 500000, maxSize: 500000,
mode: 'cover',
timeout: 10000, timeout: 10000,
} }
+1 -3
View File
@@ -257,9 +257,7 @@ export async function imageToThumb(
try { try {
const img = await downloadAndResize({ const img = await downloadAndResize({
uri: imageUri, uri: imageUri,
width: POST_IMG_MAX.width, maxDimension: POST_IMG_MAX.width,
height: POST_IMG_MAX.height,
mode: 'contain',
maxSize: POST_IMG_MAX.size, maxSize: POST_IMG_MAX.size,
timeout: 15e3, timeout: 15e3,
}) })
+6
View File
@@ -102,6 +102,12 @@ export const POST_IMG_MAX = {
size: 1000000, size: 1000000,
} }
export const POST_IMG_MAX_HIGH_RES = {
width: 4000,
height: 4000,
size: 2000000,
}
export const STAGING_LINK_META_PROXY = export const STAGING_LINK_META_PROXY =
'https://cardyb.staging.bsky.dev/v1/extract?url=' 'https://cardyb.staging.bsky.dev/v1/extract?url='
+15 -37
View File
@@ -21,7 +21,7 @@ import {logger} from '#/logger'
import {IS_ANDROID, IS_IOS} from '#/env' import {IS_ANDROID, IS_IOS} from '#/env'
import {type PickerImage} from './picker.shared' import {type PickerImage} from './picker.shared'
import {type Dimensions} from './types' import {type Dimensions} from './types'
import {convertCdnPreset} from './util' import {convertCdnPreset, getResizedDimensions} from './util'
export async function compressIfNeeded( export async function compressIfNeeded(
img: PickerImage, img: PickerImage,
@@ -31,9 +31,7 @@ export async function compressIfNeeded(
return img return img
} }
const resizedImage = await doResize(normalizePath(img.path), { const resizedImage = await doResize(normalizePath(img.path), {
width: img.width, maxDimension: POST_IMG_MAX.width,
height: img.height,
mode: 'stretch',
maxSize, maxSize,
}) })
const finalImageMovedPath = await moveToPermanentPath( const finalImageMovedPath = await moveToPermanentPath(
@@ -49,9 +47,7 @@ export async function compressIfNeeded(
export interface DownloadAndResizeOpts { export interface DownloadAndResizeOpts {
uri: string uri: string
width: number maxDimension: number
height: number
mode: 'contain' | 'cover' | 'stretch'
maxSize: number maxSize: number
timeout: number timeout: number
} }
@@ -67,7 +63,10 @@ export async function downloadAndResize(opts: DownloadAndResizeOpts) {
const path = await downloadImage(opts.uri, String(uuid.v4()), opts.timeout) const path = await downloadImage(opts.uri, String(uuid.v4()), opts.timeout)
try { try {
return await doResize(path, opts) return await doResize(path, {
maxDimension: opts.maxDimension,
maxSize: opts.maxSize,
})
} finally { } finally {
void safeDeleteAsync(path) void safeDeleteAsync(path)
} }
@@ -188,9 +187,7 @@ export function getImageDim(path: string): Promise<Dimensions> {
// = // =
interface DoResizeOpts { interface DoResizeOpts {
width: number maxDimension: number
height: number
mode: 'contain' | 'cover' | 'stretch'
maxSize: number maxSize: number
} }
@@ -204,10 +201,13 @@ async function doResize(
// Performing an "empty" manipulation lets us get the dimensions of the original image. React Native's Image.getSize() // Performing an "empty" manipulation lets us get the dimensions of the original image. React Native's Image.getSize()
// does not work for local files... // does not work for local files...
const imageRes = await manipulateAsync(localUri, [], {}) const imageRes = await manipulateAsync(localUri, [], {})
const newDimensions = getResizedDimensions({ const newDimensions = getResizedDimensions(
width: imageRes.width, {
height: imageRes.height, width: imageRes.width,
}) height: imageRes.height,
},
{width: opts.maxDimension, height: opts.maxDimension},
)
let minQualityPercentage = 0 let minQualityPercentage = 0
let maxQualityPercentage = 101 // exclusive let maxQualityPercentage = 101 // exclusive
@@ -388,28 +388,6 @@ async function withTempFile<T>(
} }
} }
export function getResizedDimensions(originalDims: {
width: number
height: number
}) {
if (
originalDims.width <= POST_IMG_MAX.width &&
originalDims.height <= POST_IMG_MAX.height
) {
return originalDims
}
const ratio = Math.min(
POST_IMG_MAX.width / originalDims.width,
POST_IMG_MAX.height / originalDims.height,
)
return {
width: Math.round(originalDims.width * ratio),
height: Math.round(originalDims.height * ratio),
}
}
async function downloadImage(uri: string, destName: string, timeout: number) { async function downloadImage(uri: string, destName: string, timeout: number) {
// Download to a temp path first, then rename with the correct extension // Download to a temp path first, then rename with the correct extension
// based on the response's mimeType. // based on the response's mimeType.
+25 -16
View File
@@ -1,6 +1,12 @@
import {POST_IMG_MAX} from '#/lib/constants'
import {type PickerImage} from './picker.shared' import {type PickerImage} from './picker.shared'
import {type Dimensions} from './types' import {type Dimensions} from './types'
import {blobToDataUri, convertCdnPreset, getDataUriSize} from './util' import {
blobToDataUri,
convertCdnPreset,
getDataUriSize,
getResizedDimensions,
} from './util'
export async function compressIfNeeded( export async function compressIfNeeded(
img: PickerImage, img: PickerImage,
@@ -10,18 +16,14 @@ export async function compressIfNeeded(
return img return img
} }
return await doResize(img.path, { return await doResize(img.path, {
width: img.width, maxDimension: POST_IMG_MAX.width,
height: img.height,
mode: 'stretch',
maxSize, maxSize,
}) })
} }
export interface DownloadAndResizeOpts { export interface DownloadAndResizeOpts {
uri: string uri: string
width: number maxDimension: number
height: number
mode: 'contain' | 'cover' | 'stretch'
maxSize: number maxSize: number
timeout: number timeout: number
} }
@@ -34,7 +36,10 @@ export async function downloadAndResize(opts: DownloadAndResizeOpts) {
clearTimeout(to) clearTimeout(to)
const dataUri = await blobToDataUri(resBody) const dataUri = await blobToDataUri(resBody)
return await doResize(dataUri, opts) return await doResize(dataUri, {
maxDimension: opts.maxDimension,
maxSize: opts.maxSize,
})
} }
export async function shareImageModal(_opts: {uri: string}) { export async function shareImageModal(_opts: {uri: string}) {
@@ -70,9 +75,7 @@ export async function getImageDim(path: string): Promise<Dimensions> {
// = // =
interface DoResizeOpts { interface DoResizeOpts {
width: number maxDimension: number
height: number
mode: 'contain' | 'cover' | 'stretch'
maxSize: number maxSize: number
} }
@@ -80,6 +83,12 @@ async function doResize(
dataUri: string, dataUri: string,
opts: DoResizeOpts, opts: DoResizeOpts,
): Promise<PickerImage> { ): Promise<PickerImage> {
const sourceDims = await getImageDim(dataUri)
const newDimensions = getResizedDimensions(sourceDims, {
width: opts.maxDimension,
height: opts.maxDimension,
})
let newDataUri let newDataUri
let minQualityPercentage = 0 let minQualityPercentage = 0
@@ -90,10 +99,10 @@ async function doResize(
(maxQualityPercentage + minQualityPercentage) / 2, (maxQualityPercentage + minQualityPercentage) / 2,
) )
const tempDataUri = await createResizedImage(dataUri, { const tempDataUri = await createResizedImage(dataUri, {
width: opts.width, width: newDimensions.width,
height: opts.height, height: newDimensions.height,
quality: qualityPercentage / 100, quality: qualityPercentage / 100,
mode: opts.mode, mode: 'contain',
}) })
if (getDataUriSize(tempDataUri) < opts.maxSize) { if (getDataUriSize(tempDataUri) < opts.maxSize) {
@@ -111,8 +120,8 @@ async function doResize(
path: newDataUri, path: newDataUri,
mime: 'image/jpeg', mime: 'image/jpeg',
size: getDataUriSize(newDataUri), size: getDataUriSize(newDataUri),
width: opts.width, width: newDimensions.width,
height: opts.height, height: newDimensions.height,
} }
} }
+24
View File
@@ -1,7 +1,31 @@
import {POST_IMG_MAX} from '#/lib/constants'
export function extractDataUriMime(uri: string): string { export function extractDataUriMime(uri: string): string {
return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')) return uri.substring(uri.indexOf(':') + 1, uri.indexOf(';'))
} }
export function getResizedDimensions(
originalDims: {
width: number
height: number
},
max: {width: number; height: number} = POST_IMG_MAX,
) {
if (originalDims.width <= max.width && originalDims.height <= max.height) {
return originalDims
}
const ratio = Math.min(
max.width / originalDims.width,
max.height / originalDims.height,
)
return {
width: Math.round(originalDims.width * ratio),
height: Math.round(originalDims.height * ratio),
}
}
// Fairly accurate estimate that is more performant // Fairly accurate estimate that is more performant
// than decoding and checking length of URI // than decoding and checking length of URI
export function getDataUriSize(uri: string): number { export function getDataUriSize(uri: string): number {
+17 -5
View File
@@ -13,6 +13,7 @@ import {
} from 'expo-image-manipulator' } from 'expo-image-manipulator'
import {nanoid} from 'nanoid/non-secure' import {nanoid} from 'nanoid/non-secure'
import {POST_IMG_MAX_HIGH_RES} from '#/lib/constants'
import {getImageDim} from '#/lib/media/manip' import {getImageDim} from '#/lib/media/manip'
import {openCropper} from '#/lib/media/picker' import {openCropper} from '#/lib/media/picker'
import {type PickerImage} from '#/lib/media/picker.shared' import {type PickerImage} from '#/lib/media/picker.shared'
@@ -201,12 +202,19 @@ export function resetImageManipulation(
return img return img
} }
export async function compressImage(img: ComposerImage): Promise<PickerImage> { export async function compressImage(
img: ComposerImage,
{
maxDimension = POST_IMG_MAX_HIGH_RES.width,
maxBytes = POST_IMG_MAX_HIGH_RES.size,
}: {maxDimension?: number; maxBytes?: number} = {},
): Promise<PickerImage> {
const source = img.transformed || img.source const source = img.transformed || img.source
let attempts = 0 let attempts = 0
let maxDimension = 4000 // Seeded from `maxDimension` but shrunk per attempt below, so keep the param
let maxBytes = 2000000 // itself pristine.
let currentDimension = maxDimension
let minQualityPercentage = 0 let minQualityPercentage = 0
let maxQualityPercentage = 101 // exclusive let maxQualityPercentage = 101 // exclusive
@@ -215,7 +223,11 @@ export async function compressImage(img: ComposerImage): Promise<PickerImage> {
while (maxQualityPercentage - minQualityPercentage > 1) { while (maxQualityPercentage - minQualityPercentage > 1) {
if (attempts >= 4) break if (attempts >= 4) break
const [w, h] = containImageRes(source.width, source.height, maxDimension) const [w, h] = containImageRes(
source.width,
source.height,
currentDimension,
)
const qualityPercentage = Math.round( const qualityPercentage = Math.round(
(maxQualityPercentage + minQualityPercentage) / 2, (maxQualityPercentage + minQualityPercentage) / 2,
) )
@@ -231,7 +243,7 @@ export async function compressImage(img: ComposerImage): Promise<PickerImage> {
maxQualityPercentage = 101 maxQualityPercentage = 101
attempts++ attempts++
// 4000px → 3200px → 2560px → 2048px → ~1638px // 4000px → 3200px → 2560px → 2048px → ~1638px
maxDimension = Math.floor(maxDimension * 0.8) currentDimension = Math.floor(currentDimension * 0.8)
continue continue
} }
@@ -16,7 +16,7 @@ import {type PasteEventPayload, TextInputWrapper} from 'expo-paste-input'
import {AppBskyRichtextFacet, RichText} from '@atproto/api' import {AppBskyRichtextFacet, RichText} from '@atproto/api'
import {useLingui} from '@lingui/react/macro' import {useLingui} from '@lingui/react/macro'
import {POST_IMG_MAX} from '#/lib/constants' import {POST_IMG_MAX_HIGH_RES} from '#/lib/constants'
import {downloadAndResize} from '#/lib/media/manip' import {downloadAndResize} from '#/lib/media/manip'
import {isUriImage} from '#/lib/media/util' import {isUriImage} from '#/lib/media/util'
import {getMentionAt, insertMentionAt} from '#/lib/strings/mention-manip' import {getMentionAt, insertMentionAt} from '#/lib/strings/mention-manip'
@@ -93,10 +93,8 @@ export function TextInput({
if (isUriImage(feature.uri)) { if (isUriImage(feature.uri)) {
const res = await downloadAndResize({ const res = await downloadAndResize({
uri: feature.uri, uri: feature.uri,
width: POST_IMG_MAX.width, maxDimension: POST_IMG_MAX_HIGH_RES.width,
height: POST_IMG_MAX.height, maxSize: POST_IMG_MAX_HIGH_RES.size,
mode: 'contain',
maxSize: POST_IMG_MAX.size,
timeout: 15e3, timeout: 15e3,
}) })