zoukankan      html  css  js  c++  java
  • [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)
  • 相关阅读:
    在C++里while语句的一个妙用
    看书——我和村上作品
    Linux下使用QQ和查看QQ空间
    Redflag 6.0 Linux下装 nvidia fx5200显卡驱动
    唇伤
    看书——我和村上作品
    Firefox 3 查看QQ空间的问题——只能开8位以下QQ的空间
    codeforces 315 B.Sereja and Array
    codeforces 285C Building Permutation
    省赛总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14587672.html
Copyright © 2011-2022 走看看