【问题标题】:try to resize the stream image with sharp Node.js尝试使用清晰的 Node.js 调整流图像的大小
【发布时间】:2019-01-29 16:31:12
【问题描述】:

我正在尝试使用清晰的功能将输入 Stream-image 的宽度和高度从用户调整到服务器,但图像没有任何反应。它保持原来的大小,我应该如何使用锐化功能才能使图像变小或变大?

请帮帮我

这是我的代码的样子:

'use strict';


const builder = require('botbuilder');
const restify = require('restify');
const utils = require('./utils.js');
const request = require('request');
const sharp = require('sharp');
const fs = require('fs');     
const resizeImage = require('resize-image');


// Create chat connector for communicating with the Bot Framework Service
const connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

// Setup Restify Server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
    console.log(`${server.name} listening to ${server.url}`);
});

// Listen for messages from users
server.post('/api/messages', connector.listen());

const bot = new builder.UniversalBot(connector);

// default dialog

//resize the images

//Sends greeting message when the bot is first added to a conversation
bot.on('conversationUpdate', function (message) {
    if (message.membersAdded) {
        message.membersAdded.forEach(function (identity) {
            if (identity.id === message.address.bot.id) {
                
         
                var reply = new builder.Message()
                    .address(message.address)
                    
                    .text('Hi, please send a screenshot for the error');
                    

                bot.send(reply);
            }
        });
    }
}
);

bot.dialog('/', function(session) {
    if(utils.hasImageAttachment(session)){
        //--others

        var stream = utils.getImageStreamFromMessage(session.message);
      ***//resize the image stream
      sharp('stream')
      .resize(100, 100)
      .toFile('stream', function(err) {
        // output.jpg is a 200 pixels wide and 200 pixels high image
        // containing a scaled and cropped version of input.jpg
      }); 
      //***
        const params = {
            'language': 'en',
            'detectOrientation': 'true',

        };
        const options = {
            uri: uriBase,
          qs: params,
            body: stream ,
          
            headers: {
                'Content-Type': 'application/octet-stream',
                'Ocp-Apim-Subscription-Key' : subscriptionKey
            }
        };

request.post(options, (error, response, body) => {
    if (error) {
      console.log('Error: ', error);
      return;
    }

 const obj =   JSON.parse(body);
 console.log(obj);

 
  //------------ get the texts from json as string
  if(obj.regions =="" ){
    
    session.send('OOOOPS I CANNOT READ ANYTHING IN THISE IMAGE :(');

}else{


let buf = ''
if(obj && obj.regions) {
obj.regions.forEach((a, b, c) => {
if(a && a.lines) {
a.lines.forEach((p, q, r) => {
if(p && p.words) {
p.words.forEach((x, y, z) => {
  

buf += ` ${x.text}  ` 



})
}
})
}
})
}
session.send(buf);
}

});
               

    } else {
        session.send('nothing');

        
    }
});

谢谢

【问题讨论】:

    标签: javascript node.js azure botframework chatbot


    【解决方案1】:

    在我的案例中,我以以下方式使用了 Sharp,效果非常好。

                sharp('stream')
                .png()
                .resize(100, 100)
                .toBuffer((err, buffer, info) => {
                    if (err)
                        console.log(err);
    
                    if (buffer) {
                        return buffer;
                    }
                });
    

    Sharp 的 toFile() 将输出保存在文件中,因此您可以提供文件名作为参数。 toBuffer() 将返回一个缓冲对象。 希望对您有所帮助!

    【讨论】:

    • 我正在尝试调整 aws s3 流的大小。就我而言,它是说Input file is missing
    【解决方案2】:

    您对 sharp('stream') 的使用不起作用,因为该函数正在寻找一个字符串作为其输入,而您正试图为其提供一个流。根据docs,您需要从 readableStream 中读取,然后处理图像。

    我(本地)测试并运行了下面的示例。照原样,它将图像文件保存在服务器上的 app.js 文件的位置。注释掉的“.pipe(stream)”创建了一个 writeableStream,如果这是您需要的,您可以在以后访问。在这种情况下,您不会使用 .toFile()。

    希望有帮助!

    bot.dialog('/', function (session) {
        if (utils.hasImageAttachment(session)) {
            //--others
    
            var stream = utils.getImageStreamFromMessage(session.message);
    
            var transformer = sharp()
                .resize(100)
                .jpeg()
                .toFile('image.jpg', function (err) {
                    if (err)
                        console.log(err);
                })
                .on('info', function (err, info) {
                    session.send('Image height is ' + info.height);
                });
            stream.pipe(transformer); //.pipe(stream);
    
            const params = {
                'language': 'en',
                'detectOrientation': 'true',
    
            };
    
            const options = {
                uri: "https://smba.trafficmanager.net/apis",
                qs: params,
                body: stream,
    
                headers: {
                    'Content-Type': 'application/octet-stream',
                    'Ocp-Apim-Subscription-Key': ""
                }
            };
    
            request.post(options, (error, response, body) => {
                if (error) {
                    console.log('Error: ', error);
                    return;
                }
    
                console.log(body);
                const obj = JSON.stringify(body);
                console.log(body);
    
    
                //------------ get the texts from json as string
                if (obj.regions == "") {
                    session.send('OOOOPS I CANNOT READ ANYTHING IN THISE IMAGE :(');
                } else {
                    let buf = ''
                    if (obj && obj.regions) {
                        obj.regions.forEach((a, b, c) => {
                            if (a && a.lines) {
                                a.lines.forEach((p, q, r) => {
                                    if (p && p.words) {
                                        p.words.forEach((x, y, z) => {
                                            buf += ` ${x.text}  `
                                        })
                                    }
                                })
                            }
                        })
                    }
                    session.send(buf);
                }
            });
        } else {
            session.send('nothing');
        }
    });
    

    【讨论】:

      【解决方案3】:

      根据函数toFile()的Sharp的文档,该函数在没有提供回调时返回一个promise。

      所以在原谅toFile函数时应该没有I/O阻塞,并在你的代码sn-p中继续运行下面的代码request.post。那时,图像可能不会被修改。

      您可以尝试使用 Promise 样式的代码流,例如:

      sharp('stream')
            .resize(100, 100)
            .toFile('stream')
            .then((err,info)=>{
               //do request post 
            })
      

      或者把请求代码放在toFile()的回调函数里面,比如:

      sharp('stream')
            .resize(100, 100)
            .toFile('stream',function(err,info)=>{
             //do request post
            })
      

      【讨论】:

      • 感谢您的回复和您的时间。我试过了,但它不起作用。我得到了同样的结果。输入图像的大小不能修改。是否有其他功能或技巧可以帮助我解决这个问题?
      猜你喜欢
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 2018-10-29
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多