File size: 1,352 Bytes
7235cc7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import path from 'path';
import fs from 'fs';
import sharp from 'sharp';
const UPLOAD_DIR = path.join(__dirname, '../uploads');
export function ensureUploadDirs() {
const dirs = [
UPLOAD_DIR,
path.join(UPLOAD_DIR, 'userpics'),
path.join(UPLOAD_DIR, 'thumbs'),
path.join(UPLOAD_DIR, 'normal')
];
for (const dir of dirs) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
}
export async function processUploadedImage(filePath: string, filename: string) {
ensureUploadDirs();
const userpicsPath = path.join(UPLOAD_DIR, 'userpics', filename);
const thumbsPath = path.join(UPLOAD_DIR, 'thumbs', filename);
const normalPath = path.join(UPLOAD_DIR, 'normal', filename);
fs.copyFileSync(filePath, userpicsPath);
const image = sharp(userpicsPath);
const metadata = await image.metadata();
const pwidth = metadata.width || 0;
const pheight = metadata.height || 0;
const stats = fs.statSync(userpicsPath);
const filesize = stats.size;
await sharp(userpicsPath)
.resize(200, 200, { fit: 'inside', withoutEnlargement: true })
.toFile(thumbsPath);
await sharp(userpicsPath)
.resize(800, 800, { fit: 'inside', withoutEnlargement: true })
.toFile(normalPath);
return {
filepath: 'userpics/',
filename,
filesize,
pwidth,
pheight
};
}
|