This commit is contained in:
Ivan Rezchikov
2026-07-11 21:21:38 +03:00
parent 18161f4604
commit 4c42b5aa1d
20 changed files with 369 additions and 260 deletions
+10 -8
View File
@@ -8,13 +8,13 @@ const BUCKET = "uploads";
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]);
export async function uploadImage(file: File, directory: string, options: { maxWidth: number; maxHeight: number; fit?: "inside" | "cover"; removeBg?: boolean }): Promise<string> {
export async function uploadImage(file: File, directory: string, options: { maxWidth?: number; maxHeight?: number; fit?: "inside" | "cover" }): Promise<string> {
if (file.size === 0) throw new AppError("A file is required");
if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
const input = Buffer.from(await file.arrayBuffer());
let image = sharp(input, {
const image = sharp(input, {
failOn: "error",
limitInputPixels: 30_000_000,
});
@@ -28,14 +28,16 @@ export async function uploadImage(file: File, directory: string, options: { maxW
throw new AppError("Image is too small");
}
const resizeOptions: Parameters<typeof image.resize>[0] = {
fit: options.fit ?? "inside",
withoutEnlargement: true,
};
if (options.maxWidth) resizeOptions.width = options.maxWidth;
if (options.maxHeight) resizeOptions.height = options.maxHeight;
const output = await image
.rotate()
.resize({
width: options.maxWidth,
height: options.maxHeight,
fit: options.fit ?? "inside",
withoutEnlargement: true,
})
.resize(resizeOptions)
.webp({ quality: 80, effort: 4 })
.toBuffer();