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)
  • 相关阅读:
    hdu 1269 迷宫城堡(强联通分量,基础)
    hdu 2102 A计划(BFS,基础)
    python 变量命名规范
    rpm常用选项
    memcached
    session共享
    Nginx高级使用
    nginx 反向代理
    Nginx基本使用
    github 建立博客
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14587672.html
Copyright © 2011-2022 走看看