如何动态调整图像大小(Express 和 S3)

How to resize image on fly(express and S3)

我正在尝试从 url 获取图像,然后在不保存的情况下动态调整大小

var request = require('request');
    request
            .get('s3url')
            .on('response', function (response) {
                console.log(response) // 200
                console.log(response.headers['content-type']) // 'image/png'
            })
            .pipe(res)

我现在可以 return 与 request lib 相同的图片,但我如何操作它然后 return 作为响应?

有几个 npm 模块可以调整大小,一个例子是 sharp。您可以以这种方式使用它(示例取自 API 文档)。

var transformer = sharp()
    .resize(300)
    .on('info', function(info) {
        console.log('Image height is ' + info.height);
    });

readableStream.pipe(transformer).pipe(res);

readableStream 将是您原始图片的流。

Sharp 的完整示例。检查 github link: https://github.com/surojitp/imageResizeOnTheFly

import express from 'express';
const app = express();
import sharp from "sharp";
import got from "got";


app.get('/',(req, res, next) =>{
    
    let image = req.query.src ? req.query.src : 'https://thumbs.dreamstime.com/b/businessman-hand-writing-demo-marker-business-concep-concept-96434578.jpg';
        
    let width = parseInt(req.query.width ? req.query.width : 100); 
    let height = parseInt(req.query.height ? req.query.height : 100);

        
    var transformer = sharp()
            .resize(width, height)
            .on('info', function(info) {
                // console.log('Image height is ' + info.height);
            });

    /********* Using GOT */
    got.stream(image).pipe(transformer).pipe(res);
});
app.listen(8080);

示例:http://localhost:8080/?src=https://buket.s3.amazonaws.com/images/defaultimg.png&&height=200&&width=200