• [Node.js] Apply image filter on Express


    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)
  • 相关阅读:
    uva 532 Dungeon Master
    hrbeu 哈工程 Tunnels
    poj 1088 滑雪
    hrbeu 哈工程 Eular Graph
    uva 567 Risk
    hrbeu 哈工程 Minimum time
    产品要不要做先回答的10个问题
    用icacls命令行给目录赋权
    SQL Server的FileStream和FileTable
    cygwin 离线安装包(包括vim,ssh,scp)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14587672.html
Copyright © 2020-2023  润新知