Working display and resize
parent
7f83cb6d16
commit
9af57a4e49
Binary file not shown.
After Width: | Height: | Size: 28 KiB |
@ -1,26 +1,58 @@
|
|||||||
import express from "express"
|
import express from "express"
|
||||||
import path from "path"
|
|
||||||
import fs from "fs"
|
import fs from "fs"
|
||||||
|
import path from "path"
|
||||||
|
import sharp from "sharp"
|
||||||
|
|
||||||
const image = express.Router();
|
const image = express.Router();
|
||||||
|
|
||||||
image.get('/',
|
const resizeImg = async (width: number, height: number, inputimgPath: string, fileName: string): Promise<string> => {
|
||||||
async (req: express.Request, res: express.Response): Promise<void> => {
|
// output file for resized img
|
||||||
let filename = req.query.filename as string;
|
let outputImg = path.resolve("images/thumb", `${fileName}.jpg`);
|
||||||
|
await sharp(path.resolve(inputimgPath))
|
||||||
try {
|
.resize(width, height)
|
||||||
let filePath = path.resolve("images/full", `${filename}.jpg`);
|
.toFormat("jpeg")
|
||||||
console.log('FILE PATH', filePath);
|
.jpeg({
|
||||||
if (!fs.existsSync(filePath)) {
|
quality: 100,
|
||||||
res.status(404).send("Image don't exist! Try another name");
|
mozjpeg: true
|
||||||
return;
|
})
|
||||||
}
|
.toFile(path.resolve(outputImg))
|
||||||
res.sendFile(filePath);
|
|
||||||
} catch (err) {
|
return outputImg
|
||||||
res.status(404).send(`An error occured`);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
//res.send('Welcome to image route please add parametres in the url');
|
|
||||||
})
|
|
||||||
|
image.get('/', async (req: express.Request, res: express.Response): Promise<void> => {
|
||||||
|
let fileName = req.query.filename as string;
|
||||||
|
let width = parseInt(req.query.width as string);
|
||||||
|
let height = parseInt(req.query.height as string);
|
||||||
|
|
||||||
|
// fetch file from server
|
||||||
|
let inputimgPath: string = path.resolve("images/full", `${fileName}.jpg`);
|
||||||
|
|
||||||
|
|
||||||
|
// check if the inputFile exist
|
||||||
|
if (!fs.existsSync(inputimgPath)) {
|
||||||
|
res.status(404).send("Image not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// display image if we have fileName, width, height attributs in the request
|
||||||
|
if (fileName && width && height) {
|
||||||
|
|
||||||
|
//resize image
|
||||||
|
let outputImg: string = await resizeImg(width, height, inputimgPath, fileName);
|
||||||
|
res.sendFile(outputImg);
|
||||||
|
|
||||||
|
} else if (fileName) {
|
||||||
|
// display original image if we only have filename parameter in the request
|
||||||
|
res.sendFile(inputimgPath);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export default image;
|
export default image;
|
Loading…
Reference in New Issue