chore: moved util to a dedicated service file

This commit is contained in:
Chesterkxng committed 2026-08-07 17:34:02 +02:00
1 parent 3f7a9497a1
commit 9d54447d5b
2 files changed
+81 -97

No files matched your search

@@ -1,5 +1,5 @@
import { Box } from '@mui/material';
import React, { useRef, useState } from 'react';
import React, { useState, useCallback } from 'react';
import ToolFileResult from '@components/result/ToolFileResult';
import TextFieldWithDesc from 'components/options/TextFieldWithDesc';
import ToolContent from '@components/ToolContent';
@@ -7,11 +7,11 @@ import { ToolComponentProps } from '@tools/defineTool';
import ToolMultipleImageInput, {
MultiImageInput
} from '@components/input/ToolMultipleImageInput';
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile } from '@ffmpeg/util';
import { InitialValuesType } from './types';
import { updateNumberField } from '@utils/string';
import { useTranslation } from 'react-i18next';
import { imagesToGif } from './service';
import { debounce } from 'lodash';
const initialValues: InitialValuesType = {
frameDelay: 500
@@ -23,102 +23,26 @@ export default function ImagesToGif({ title }: ToolComponentProps) {
const [result, setResult] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const ffmpegRef = useRef<FFmpeg | null>(null);
const ffmpegLoadedRef = useRef(false);
const processingRef = useRef(false);
const compute = (
const compute = async (
optionsValues: InitialValuesType,
input: MultiImageInput[]
) => {
if (!input || input.length === 0) return;
if (processingRef.current) return;
const { frameDelay } = optionsValues;
const processImages = async (): Promise<void> => {
processingRef.current = true;
setLoading(true);
setResult(null);
if (!ffmpegRef.current) {
ffmpegRef.current = new FFmpeg();
}
const ffmpeg = ffmpegRef.current;
if (!ffmpegLoadedRef.current) {
await ffmpeg.load({
coreURL:
'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.js',
wasmURL:
'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm'
});
ffmpegLoadedRef.current = true;
}
const fileNames: string[] = [];
try {
const durationSeconds = frameDelay / 1000;
for (let i = 0; i < input.length; i++) {
const file = input[i].file;
const ext = file.name.split('.').pop()?.toLowerCase() || 'jpg';
const fname = `frame${i.toString().padStart(4, '0')}.${ext}`;
fileNames.push(fname);
await ffmpeg.writeFile(fname, await fetchFile(file));
}
const listContent =
fileNames
.map((f) => `file '${f}'\nduration ${durationSeconds}`)
.join('\n') + `\nfile '${fileNames[fileNames.length - 1]}'`;
await ffmpeg.writeFile('list.txt', listContent);
await ffmpeg.exec([
'-f',
'concat',
'-safe',
'0',
'-i',
'list.txt',
'-vf',
'scale=480:-2:flags=lanczos',
'-loop',
'0',
'output.gif'
]);
const data = await ffmpeg.readFile('output.gif');
const blob = new Blob([data as any], { type: 'image/gif' });
setResult(new File([blob], 'animated.gif', { type: 'image/gif' }));
} finally {
for (const fname of fileNames) {
try {
await ffmpeg.deleteFile(fname);
} catch {
/* ignore */
}
}
try {
await ffmpeg.deleteFile('list.txt');
} catch {
/* ignore */
}
try {
await ffmpeg.deleteFile('output.gif');
} catch {
/* ignore */
}
setLoading(false);
processingRef.current = false;
}
};
processImages();
try {
const convertedGif = await imagesToGif(
input.map((item) => item.file),
optionsValues
);
setResult(convertedGif);
} catch (error) {
console.error('Error cropping video:', error);
} finally {
setLoading(false);
}
};
const debouncedCompute = useCallback(debounce(compute, 1000), []);
return (
<ToolContent
title={title}
@@ -152,16 +76,20 @@ export default function ImagesToGif({ title }: ToolComponentProps) {
type="number"
inputProps={{ min: 50, max: 10000, step: 50 }}
description={t('gif.imagesToGif.frameDelayDescription')}
onOwnChange={(value) =>
updateNumberField(value, 'frameDelay', updateField)
}
onOwnChange={(value) => {
const clamped = Math.min(
10000,
Math.max(50, Number(value))
).toString();
updateNumberField(clamped, 'frameDelay', updateField);
}}
value={values.frameDelay}
/>
</Box>
)
}
]}
compute={compute}
compute={debouncedCompute}
setInput={setInput}
/>
);
@@ -0,0 +1,56 @@
import { runFFmpegTask } from 'lib/ffmpeg';
import { fetchFile } from '@ffmpeg/util';
import { InitialValuesType } from './types';
import { getFileExtension } from '@utils/file';
export async function imagesToGif(
input: File[],
optionsValues: InitialValuesType
): Promise<File> {
return runFFmpegTask(async ({ ffmpeg, tempFile }) => {
const { frameDelay } = optionsValues;
const fileNames: string[] = [];
const listName = tempFile('.txt');
const outputName = tempFile('.gif');
const durationSeconds = frameDelay / 1000;
for (let i = 0; i < input.length; i++) {
const file = input[i];
const ext = getFileExtension(file.name) ?? 'jpg';
const inputName = tempFile(`.${ext}`);
fileNames.push(inputName);
await ffmpeg.writeFile(inputName, await fetchFile(file));
}
const listContent =
fileNames
.map((name) => `file '${name}'\nduration ${durationSeconds}`)
.join('\n') + `\nfile '${fileNames[fileNames.length - 1]}'`;
await ffmpeg.writeFile(listName, listContent);
await ffmpeg.exec([
'-f',
'concat',
'-safe',
'0',
'-i',
listName,
'-vf',
'scale=480:-2:flags=lanczos',
'-loop',
'0',
outputName
]);
const data = await ffmpeg.readFile(outputName);
return new File([new Uint8Array(data as Uint8Array)], 'animated.gif', {
type: 'image/gif'
});
});
}