| 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 |
| }; |
| } |
|
|