首页 > 移动平台 > 详细

[Node.js] Apply image filter on Express

时间:2021-03-28 11:18:03      阅读:24      评论:0      收藏:0      [点我收藏+]
import fs from ‘fs‘;
import Jimp = require(‘jimp‘);

// filterImageFromURL
// helper function to download, filter, and save the filtered image locally
// returns the absolute path to the local image
// INPUTS
//    inputURL: string - a publicly accessible url to an image file
// RETURNS
//    an absolute path to a filtered image locally saved file
export async function filterImageFromURL(inputURL: string): Promise<string>{
    return new Promise( async resolve => {
        const photo = await Jimp.read(inputURL);
        const outpath = ‘/tmp/filtered.‘+Math.floor(Math.random() * 2000)+‘.jpg‘;
        await photo
        .resize(256, 256) // resize
        .quality(60) // set JPEG quality
        .greyscale() // set greyscale
        .write(__dirname+outpath, (img)=>{
            resolve(__dirname+outpath);
        });
    });
}

// deleteLocalFiles
// helper function to delete files on the local disk
// useful to cleanup after tasks
// INPUTS
//    files: Array<string> an array of absolute paths to files
export async function deleteLocalFiles(files:Array<string>){
    for( let file of files) {
        fs.unlinkSync(file);
    }
}

 

Endpoint:

  app.get(‘/filteredimage‘, async (req: Request, res: Response) => {
    const {image_url} = req.query;
    if (!image_url) {
      return res.status(422).send({
        message: `image_url query param is required`
      })
    }
    const filtered_img_path = await filterImageFromURL(image_url.toString())
    res.sendFile(filtered_img_path);
    allFiles.push(filtered_img_path);
  })

 

We want to delete previously generate files from local, this can be done by using middleware:

  let allFiles: string[] = [];
  const cleanUp = (req: Request, res: Response, next: NextFunction) => {
    const sendFile = res.sendFile.bind(res);
    res.sendFile = (body: any) => {
      sendFile(body);
      deleteLocalFiles(allFiles)
      allFiles = [];
    }
    next();
  }

  app.use(‘/‘, cleanUp)

 

[Node.js] Apply image filter on Express

原文:https://www.cnblogs.com/Answer1215/p/14587672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!