From 9d54447d5ba25952bcdedbd8094074bf3368f0df Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Fri, 7 Aug 2026 17:34:02 +0200 Subject: [PATCH] chore: moved util to a dedicated service file --- .../tools/video/gif/images-to-gif/index.tsx | 122 ++++-------------- .../tools/video/gif/images-to-gif/service.ts | 56 ++++++++ 2 files changed, 81 insertions(+), 97 deletions(-) create mode 100644 src/pages/tools/video/gif/images-to-gif/service.ts diff --git a/src/pages/tools/video/gif/images-to-gif/index.tsx b/src/pages/tools/video/gif/images-to-gif/index.tsx index 5d134ce2..de510c17 100644 --- a/src/pages/tools/video/gif/images-to-gif/index.tsx +++ b/src/pages/tools/video/gif/images-to-gif/index.tsx @@ -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(null); const [loading, setLoading] = useState(false); - const ffmpegRef = useRef(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 => { - 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 ( - updateNumberField(value, 'frameDelay', updateField) - } + onOwnChange={(value) => { + const clamped = Math.min( + 10000, + Math.max(50, Number(value)) + ).toString(); + updateNumberField(clamped, 'frameDelay', updateField); + }} value={values.frameDelay} /> ) } ]} - compute={compute} + compute={debouncedCompute} setInput={setInput} /> ); diff --git a/src/pages/tools/video/gif/images-to-gif/service.ts b/src/pages/tools/video/gif/images-to-gif/service.ts new file mode 100644 index 00000000..6076428f --- /dev/null +++ b/src/pages/tools/video/gif/images-to-gif/service.ts @@ -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 { + 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' + }); + }); +}