ly0303521

1M以上的图片将会被压缩之后上传

import { TURBO_DIFFUSION_API_URL } from '../constants';
import { VideoStatus } from '../types';
const compressImage = async (file: File): Promise<File> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
const img = new Image();
img.src = event.target?.result as string;
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
const MAX_SIZE = 1024;
if (width > height) {
if (width > MAX_SIZE) {
height *= MAX_SIZE / width;
width = MAX_SIZE;
}
} else {
if (height > MAX_SIZE) {
width *= MAX_SIZE / height;
height = MAX_SIZE;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
if (blob) {
const compressedFile = new File([blob], file.name, {
type: 'image/jpeg',
lastModified: Date.now(),
});
resolve(compressedFile);
} else {
reject(new Error('Canvas is empty'));
}
}, 'image/jpeg', 0.85);
};
img.onerror = (error) => reject(error);
};
reader.onerror = (error) => reject(error);
});
};
/**
* Submits a video generation job to the backend.
* @returns The task ID for the submitted job.
*/
export const submitVideoJob = async (prompt: string, image: File, authorId: string, seed: number): Promise<string> => {
let finalImage = image;
if (image.size > 1024 * 1024) {
finalImage = await compressImage(image);
}
const formData = new FormData();
formData.append('prompt', prompt);
formData.append('image', image, image.name);
formData.append('image', finalImage, finalImage.name);
formData.append('author_id', authorId);
formData.append('seed', seed.toString());
... ... @@ -44,7 +97,10 @@ export const pollVideoStatus = (
try {
const res = await fetch(`${TURBO_DIFFUSION_API_URL}/status/${taskId}`);
if (!res.ok) {
// Stop polling on HTTP error
if (res.status === 502 || res.status === 504) {
console.warn(`Gateway timeout (${res.status}), retrying poll...`);
return;
}
clearInterval(interval);
reject(new Error(`HTTP error! status: ${res.status}`));
return;
... ...