Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
40425d1
Initial implementation of image stitching for Odometer
jakubkalinski0 Feb 26, 2026
3f840aa
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 3, 2026
5fbbcaf
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 3, 2026
d1f1717
improvement: moved imageStitching feature from hooks to lib
jakubkalinski0 Mar 3, 2026
e32a3ee
feature: when only 1 odometer image exist set it as a receipt
jakubkalinski0 Mar 3, 2026
b021cc8
improvement: added stitchLayout to make code DRY
jakubkalinski0 Mar 3, 2026
a7959e1
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 4, 2026
81b3f51
fix: added catch error handling to image stitching
jakubkalinski0 Mar 4, 2026
93bec81
fix: added revokeObjectURL of a stitched image
jakubkalinski0 Mar 4, 2026
dff2791
improvement: added error to display for user when navigateToNextPage …
jakubkalinski0 Mar 4, 2026
c77e153
improvement: small adjustments to comments in imageStitching
jakubkalinski0 Mar 4, 2026
bb6b774
fix: added file cleanup to native image stitching
jakubkalinski0 Mar 4, 2026
d61057a
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 10, 2026
df136c7
fix: added async to navigateToNextPage
jakubkalinski0 Mar 10, 2026
c831f96
fix: remove fallback to receipt source to avoid receipt flash on odom…
jakubkalinski0 Mar 10, 2026
f74f113
fix: preserve filename for camera-captured odometer image on mWeb
jakubkalinski0 Mar 10, 2026
ea7bd64
improvement: move error handling from stitchOdometerImages to caller
jakubkalinski0 Mar 11, 2026
ce37aed
fix: hide replace button for stitched odometer receipt
jakubkalinski0 Mar 11, 2026
d5f5d5d
improvement: scale images to match shared edge length when stitching
jakubkalinski0 Mar 11, 2026
d36ad3a
fix: use contain resize mode for stitched odometer receipt preview
jakubkalinski0 Mar 11, 2026
4b0ed83
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 11, 2026
c78936a
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 12, 2026
e3810a0
fix: added XYWH to cspell.json as an acceptable word
jakubkalinski0 Mar 12, 2026
18e5d32
added translations
jakubkalinski0 Mar 12, 2026
729c537
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 12, 2026
e77527f
Merge branch 'main' into jakubkalinski0/Odometer_Add_merged_image_flow
jakubkalinski0 Mar 13, 2026
4976987
fix: use isOdometerDistanceRequest util instead of filename-based odo…
jakubkalinski0 Mar 13, 2026
072e926
chore: prettier run
jakubkalinski0 Mar 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,7 @@
"xmlgateway",
"Xours",
"Xtheirs",
"XYWH",
"yalc",
"Yapl",
"YAPL",
Expand Down
2 changes: 2 additions & 0 deletions src/components/MoneyRequestConfirmationListFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,7 @@ function MoneyRequestConfirmationListFooter({
shouldUseInitialObjectPosition={isDistanceRequest}
shouldUseFullHeight={isCompactMode}
onLoad={handleReceiptLoad}
resizeMode={isOdometerDistanceRequest ? 'contain' : undefined}
/>
</PressableWithoutFocus>
)}
Expand Down Expand Up @@ -1181,6 +1182,7 @@ function MoneyRequestConfirmationListFooter({
receiptThumbnail,
fileExtension,
isDistanceRequest,
isOdometerDistanceRequest,
handleReceiptLoad,
handleCompactReceiptContainerLayout,
]);
Expand Down
1 change: 1 addition & 0 deletions src/languages/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1451,6 +1451,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: 'Das Enddatum darf nicht mit dem Startdatum übereinstimmen',
manySplitsProvided: `Die maximale Anzahl zulässiger Aufteilungen beträgt ${CONST.IOU.SPLITS_LIMIT}.`,
dateRangeExceedsMaxDays: `Der Datumsbereich darf ${CONST.IOU.SPLITS_LIMIT} Tage nicht überschreiten.`,
stitchOdometerImagesFailed: 'Kilometerzählerbilder konnten nicht zusammengeführt werden. Bitte versuchen Sie es später noch einmal.',
},
dismissReceiptError: 'Fehler ausblenden',
dismissReceiptErrorConfirmation: 'Achtung! Wenn du diesen Fehler schließt, wird deine hochgeladene Quittung vollständig entfernt. Bist du sicher?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1452,6 +1452,7 @@ const translations = {
distanceAmountTooLargeReduceDistance: 'The total amount is too large. Reduce the distance.',
distanceAmountTooLargeReduceRate: 'The total amount is too large. Lower the rate.',
odometerReadingTooLarge: (formattedMax: string) => `Odometer readings cannot exceed ${formattedMax}.`,
stitchOdometerImagesFailed: 'Failed to combine odometer images. Please try again later.',
invalidIntegerAmount: 'Please enter a whole dollar amount before continuing',
invalidTaxAmount: (amount: string) => `Maximum tax amount is ${amount}`,
invalidSplit: 'The sum of splits must equal the total amount',
Expand Down
1 change: 1 addition & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1293,6 +1293,7 @@ const translations: TranslationDeepObject<typeof en> = {
distanceAmountTooLargeReduceDistance: 'El importe total es demasiado alto. Reduce la distancia.',
distanceAmountTooLargeReduceRate: 'El importe total es demasiado alto. Disminuye la tarifa.',
odometerReadingTooLarge: (formattedMax: string) => `Las lecturas del odómetro no pueden superar ${formattedMax}.`,
stitchOdometerImagesFailed: 'No se pudieron combinar las imágenes del odómetro. Por favor, inténtalo de nuevo más tarde.',
invalidIntegerAmount: 'Por favor, introduce una cantidad entera en dólares antes de continuar',
invalidTaxAmount: (amount) => `El importe máximo del impuesto es ${amount}`,
invalidSplit: 'La suma de las partes debe ser igual al importe total',
Expand Down
1 change: 1 addition & 0 deletions src/languages/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1455,6 +1455,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: 'La date de fin ne peut pas être identique à la date de début',
manySplitsProvided: `Le nombre maximal de répartitions autorisées est de ${CONST.IOU.SPLITS_LIMIT}.`,
dateRangeExceedsMaxDays: `La plage de dates ne peut pas dépasser ${CONST.IOU.SPLITS_LIMIT} jours.`,
stitchOdometerImagesFailed: 'Échec de la combinaison des images de l’odomètre. Veuillez réessayer plus tard.',
},
dismissReceiptError: 'Ignorer l’erreur',
dismissReceiptErrorConfirmation: 'Attention ! Ignorer cette erreur supprimera complètement votre reçu téléversé. Êtes-vous sûr ?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1448,6 +1448,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: 'La data di fine non può essere uguale alla data di inizio',
manySplitsProvided: `Il numero massimo di suddivisioni consentite è ${CONST.IOU.SPLITS_LIMIT}.`,
dateRangeExceedsMaxDays: `L’intervallo di date non può superare ${CONST.IOU.SPLITS_LIMIT} giorni.`,
stitchOdometerImagesFailed: 'Impossibile combinare le immagini del contachilometri. Riprova più tardi.',
},
dismissReceiptError: 'Ignora errore',
dismissReceiptErrorConfirmation: 'Attenzione! Chiudere questo errore rimuoverà completamente la ricevuta che hai caricato. Sei sicuro?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1439,6 +1439,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: '終了日は開始日と同じにはできません',
manySplitsProvided: `分割できる最大数は${CONST.IOU.SPLITS_LIMIT}件です。`,
dateRangeExceedsMaxDays: `日付範囲は${CONST.IOU.SPLITS_LIMIT}日を超えることはできません。`,
stitchOdometerImagesFailed: '走行距離計の画像を結合できませんでした。後でもう一度お試しください。',
},
dismissReceiptError: 'エラーを閉じる',
dismissReceiptErrorConfirmation: 'ご注意ください!このエラーを閉じると、アップロード済みのレシートが完全に削除されます。本当に続行しますか?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/nl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1446,6 +1446,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: 'De einddatum mag niet gelijk zijn aan de startdatum',
manySplitsProvided: `Het maximale aantal toegestane splitsingen is ${CONST.IOU.SPLITS_LIMIT}.`,
dateRangeExceedsMaxDays: `Het datumbereik mag niet meer dan ${CONST.IOU.SPLITS_LIMIT} dagen zijn.`,
stitchOdometerImagesFailed: 'Odometerafbeeldingen combineren mislukt. Probeer het later opnieuw.',
},
dismissReceiptError: 'Foutmelding sluiten',
dismissReceiptErrorConfirmation: 'Let op! Dit foutbericht negeren verwijdert je geüploade bon volledig. Weet je het zeker?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1445,6 +1445,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: 'Data zakończenia nie może być taka sama jak data rozpoczęcia',
manySplitsProvided: `Maksymalna dozwolona liczba podziałów to ${CONST.IOU.SPLITS_LIMIT}.`,
dateRangeExceedsMaxDays: `Zakres dat nie może przekraczać ${CONST.IOU.SPLITS_LIMIT} dni.`,
stitchOdometerImagesFailed: 'Nie udało się połączyć zdjęć licznika kilometrów. Spróbuj ponownie później.',
},
dismissReceiptError: 'Odrzuć błąd',
dismissReceiptErrorConfirmation: 'Uwaga! Zamknięcie tego błędu spowoduje całkowite usunięcie przesłanego paragonu. Czy na pewno chcesz kontynuować?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1443,6 +1443,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: 'A data de término não pode ser igual à data de início',
manySplitsProvided: `O número máximo de divisões permitido é ${CONST.IOU.SPLITS_LIMIT}.`,
dateRangeExceedsMaxDays: `O intervalo de datas não pode exceder ${CONST.IOU.SPLITS_LIMIT} dias.`,
stitchOdometerImagesFailed: 'Falha ao combinar imagens do hodômetro. Tente novamente mais tarde.',
},
dismissReceiptError: 'Dispensar erro',
dismissReceiptErrorConfirmation: 'Atenção! Ignorar este erro removerá completamente o comprovante que você enviou. Tem certeza?',
Expand Down
1 change: 1 addition & 0 deletions src/languages/zh-hans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,7 @@ const translations: TranslationDeepObject<typeof en> = {
endDateSameAsStartDate: '结束日期不能与开始日期相同',
manySplitsProvided: `允许的最大拆分数为 ${CONST.IOU.SPLITS_LIMIT}。`,
dateRangeExceedsMaxDays: `日期范围不能超过 ${CONST.IOU.SPLITS_LIMIT} 天。`,
stitchOdometerImagesFailed: '合并里程表图片失败。请稍后重试。',
},
dismissReceiptError: '忽略错误',
dismissReceiptErrorConfirmation: '提醒:关闭此错误将彻底删除你上传的收据。确定要继续吗?',
Expand Down
4 changes: 2 additions & 2 deletions src/libs/actions/IOU/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -772,7 +772,7 @@
};

let allPersonalDetails: OnyxTypes.PersonalDetailsList = {};
Onyx.connect({

Check warning on line 775 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
allPersonalDetails = value ?? {};
Expand Down Expand Up @@ -872,7 +872,7 @@
};

let allTransactions: NonNullable<OnyxCollection<OnyxTypes.Transaction>> = {};
Onyx.connect({

Check warning on line 875 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -886,7 +886,7 @@
});

let allTransactionDrafts: NonNullable<OnyxCollection<OnyxTypes.Transaction>> = {};
Onyx.connect({

Check warning on line 889 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION_DRAFT,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -895,7 +895,7 @@
});

let allTransactionViolations: NonNullable<OnyxCollection<OnyxTypes.TransactionViolations>> = {};
Onyx.connect({

Check warning on line 898 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -909,7 +909,7 @@
});

let allPolicyTags: OnyxCollection<OnyxTypes.PolicyTagLists> = {};
Onyx.connect({

Check warning on line 912 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.POLICY_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -922,7 +922,7 @@
});

let allReports: OnyxCollection<OnyxTypes.Report>;
Onyx.connect({

Check warning on line 925 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -931,7 +931,7 @@
});

let allReportNameValuePairs: OnyxCollection<OnyxTypes.ReportNameValuePairs>;
Onyx.connect({

Check warning on line 934 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -941,7 +941,7 @@

let userAccountID = -1;
let currentUserEmail = '';
Onyx.connect({

Check warning on line 944 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.SESSION,
callback: (value) => {
currentUserEmail = value?.email ?? '';
Expand All @@ -950,7 +950,7 @@
});

let deprecatedCurrentUserPersonalDetails: OnyxEntry<OnyxTypes.PersonalDetails>;
Onyx.connect({

Check warning on line 953 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
deprecatedCurrentUserPersonalDetails = value?.[userAccountID] ?? undefined;
Expand All @@ -958,7 +958,7 @@
});

let allReportActions: OnyxCollection<OnyxTypes.ReportActions>;
Onyx.connect({

Check warning on line 961 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
Expand Down Expand Up @@ -1670,13 +1670,13 @@
* @param file - The image file (File object on web, URI string on native)
* @param isDraft - Whether this is a draft transaction
*/
function setMoneyRequestOdometerImage(transactionID: string, imageType: OdometerImageType, file: File | string, isDraft: boolean) {
function setMoneyRequestOdometerImage(transactionID: string, imageType: OdometerImageType, file: FileObject | string, isDraft: boolean) {
const imageKey = imageType === CONST.IOU.ODOMETER_IMAGE_TYPE.START ? 'odometerStartImage' : 'odometerEndImage';
const normalizedFile: FileObject | string =
typeof file === 'string'
? file
: {
uri: file.uri ?? (typeof URL !== 'undefined' ? URL.createObjectURL(file) : undefined),
uri: file.uri ?? (typeof URL !== 'undefined' ? URL.createObjectURL(file as Blob) : undefined),
name: file.name,
type: file.type,
size: file.size,
Expand Down
68 changes: 68 additions & 0 deletions src/libs/stitchOdometerImages/index.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {Skia} from '@shopify/react-native-skia';
import RNFS from 'react-native-fs';
import Log from '@libs/Log';
import type {FileObject} from '@src/types/utils/Attachment';
import calculateStitchLayout from './stitchLayout';

async function stitchOdometerImages(image1: FileObject | string | undefined, image2: FileObject | string | undefined): Promise<FileObject | null> {
const source1 = typeof image1 === 'string' ? image1 : (image1?.uri ?? null);
const source2 = typeof image2 === 'string' ? image2 : (image2?.uri ?? null);

if (!source1 || !source2) {
return null;
}

let skImage1 = null;
let skImage2 = null;
let surface = null;
let snapshot = null;

try {
const [buffer1, buffer2] = await Promise.all([fetch(source1).then((r) => r.arrayBuffer()), fetch(source2).then((r) => r.arrayBuffer())]);

skImage1 = Skia.Image.MakeImageFromEncoded(Skia.Data.fromBytes(new Uint8Array(buffer1)));
skImage2 = Skia.Image.MakeImageFromEncoded(Skia.Data.fromBytes(new Uint8Array(buffer2)));

if (!skImage1 || !skImage2) {
throw new Error('Failed to decode odometer images');
}

const {width, height, img1Dest, img2Dest} = calculateStitchLayout(skImage1.width(), skImage1.height(), skImage2.width(), skImage2.height());

surface = Skia.Surface.MakeOffscreen(width, height);
if (!surface) {
throw new Error('Failed to create Skia surface');
}

const canvas = surface.getCanvas();
const paint = Skia.Paint();
canvas.drawImageRect(skImage1, Skia.XYWHRect(0, 0, skImage1.width(), skImage1.height()), Skia.XYWHRect(img1Dest.x, img1Dest.y, img1Dest.w, img1Dest.h), paint);
canvas.drawImageRect(skImage2, Skia.XYWHRect(0, 0, skImage2.width(), skImage2.height()), Skia.XYWHRect(img2Dest.x, img2Dest.y, img2Dest.w, img2Dest.h), paint);
surface.flush();

snapshot = surface.makeImageSnapshot();
const base64 = snapshot.encodeToBase64();

// Delete any previously stitched files before creating a new one
try {
const tempDirContents = await RNFS.readDir(RNFS.TemporaryDirectoryPath);
const oldStitchedFiles = tempDirContents.filter((f) => f.name.startsWith('stitched_odometer_') && f.name.endsWith('.jpg'));
await Promise.all(oldStitchedFiles.map((f) => RNFS.unlink(f.path)));
} catch (error) {
Log.warn('stitchOdometerImages (native) failed to clean up old stitched files', {error});
}

const filename = `stitched_odometer_${Date.now()}.jpg`;
const tempPath = `${RNFS.TemporaryDirectoryPath}/${filename}`;
await RNFS.writeFile(tempPath, base64, 'base64');

return {uri: `file://${tempPath}`, name: filename, type: 'image/jpeg'};
} finally {
skImage1?.dispose?.();
skImage2?.dispose?.();
snapshot?.dispose?.();
surface?.dispose?.();
}
}

export default stitchOdometerImages;
54 changes: 54 additions & 0 deletions src/libs/stitchOdometerImages/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type {FileObject} from '@src/types/utils/Attachment';
import calculateStitchLayout from './stitchLayout';

// Tracks the single active stitched blob URL so that we can revoke it on the next call so at most one blob URL exists at a time
let previousBlobUrl: string | null = null;

function stitchOdometerImages(image1: FileObject | string | undefined, image2: FileObject | string | undefined): Promise<FileObject | null> {
const source1 = typeof image1 === 'string' ? image1 : (image1?.uri ?? null);
const source2 = typeof image2 === 'string' ? image2 : (image2?.uri ?? null);

if (!source1 || !source2) {
return Promise.resolve(null);
}

const loadImage = (src: string): Promise<HTMLImageElement> =>
new Promise((resolve, reject) => {
const img = new window.Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});

return Promise.all([loadImage(source1), loadImage(source2)]).then(([img1, img2]) => {
const {width, height, img1Dest, img2Dest} = calculateStitchLayout(img1.width, img1.height, img2.width, img2.height);

const offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = width;
offscreenCanvas.height = height;
const ctx = offscreenCanvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to get canvas context');
}

ctx.drawImage(img1, img1Dest.x, img1Dest.y, img1Dest.w, img1Dest.h);
ctx.drawImage(img2, img2Dest.x, img2Dest.y, img2Dest.w, img2Dest.h);

return new Promise<FileObject | null>((resolve, reject) => {
offscreenCanvas.toBlob((blob) => {
if (!blob) {
reject(new Error('Canvas toBlob returned null'));
return;
}
if (previousBlobUrl) {
URL.revokeObjectURL(previousBlobUrl);
}
const uri = URL.createObjectURL(blob);
previousBlobUrl = uri;
resolve({uri, name: 'stitched_odometer.jpg', type: 'image/jpeg'});
}, 'image/jpeg');
});
});
}

export default stitchOdometerImages;
50 changes: 50 additions & 0 deletions src/libs/stitchOdometerImages/stitchLayout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
type ImageRect = {x: number; y: number; w: number; h: number};

type StitchLayout = {
width: number;
height: number;
horizontal: boolean;
img1Dest: ImageRect;
img2Dest: ImageRect;
};

/**
* Calculates the layout for stitching two odometer images into a single combined image.
*
* Stitching rules:
* - Images are merged horizontally (side-by-side) by default
* - If either image is landscape, images are merged vertically (stacked)
* - The smaller image is resized so the shared edge matches the length of the larger image's shared edge
*/

function calculateStitchLayout(w1: number, h1: number, w2: number, h2: number): StitchLayout {
const horizontal = !(w1 > h1 || w2 > h2);

if (horizontal) {
// Side-by-side: scale both images to the same height so the shared vertical edges match
const targetH = Math.max(h1, h2);
const scaledW1 = Math.round((w1 * targetH) / h1);
const scaledW2 = Math.round((w2 * targetH) / h2);
return {
width: scaledW1 + scaledW2,
height: targetH,
horizontal: true,
img1Dest: {x: 0, y: 0, w: scaledW1, h: targetH},
img2Dest: {x: scaledW1, y: 0, w: scaledW2, h: targetH},
};
}

// Stacked: scale both images to the same width so the shared horizontal edges match
const targetW = Math.max(w1, w2);
const scaledH1 = Math.round((h1 * targetW) / w1);
const scaledH2 = Math.round((h2 * targetW) / w2);
return {
width: targetW,
height: scaledH1 + scaledH2,
horizontal: false,
img1Dest: {x: 0, y: 0, w: targetW, h: scaledH1},
img2Dest: {x: 0, y: scaledH1, w: targetW, h: scaledH2},
};
}

export default calculateStitchLayout;
Loading
Loading