【问题标题】:How to resize image on fly(express and S3)如何即时调整图像大小(快递和 S3)
【发布时间】:2022-01-23 21:00:16
【问题描述】:

我正在尝试从 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)

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

【问题讨论】:

  • 那么您是如何解决的呢?能否提供代码

标签: node.js express amazon-s3 image-resizing


【解决方案1】:

有几个 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 将是您原始图片的流。

【讨论】:

【解决方案2】:

夏普的完整示例。查看github链接: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

【讨论】:

    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多