首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试用锐利的Node.js调整流图像的大小

尝试用锐利的Node.js调整流图像的大小
EN

Stack Overflow用户
提问于 2018-08-23 10:09:26
回答 3查看 11.5K关注 0票数 3

我试图调整输入流图像的宽度和高度,从用户到具有尖锐功能的服务器,但是图像不会发生任何变化。它保持原来的大小,我应该如何使用锐利的功能,以使我可以得到更小或更大的图像?

请帮帮我

我的代码是这样的:

代码语言:javascript
复制
'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');

        
    }
});

谢谢

EN

回答 3

Stack Overflow用户

发布于 2018-08-24 04:57:11

根据函数toFile()的Sharp文档,当不提供回调时,该函数将返回一个承诺。

因此,当不使用toFile函数时,应该不存在I/O块,并继续运行下面的代码片段中的request.post代码。那时,图像可能不会被修改。

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

代码语言:javascript
复制
sharp('stream')
      .resize(100, 100)
      .toFile('stream')
      .then((err,info)=>{
         //do request post 
      })

或者将请求代码放入toFile()的回调函数中,如:

代码语言:javascript
复制
sharp('stream')
      .resize(100, 100)
      .toFile('stream',function(err,info)=>{
       //do request post
      })
票数 1
EN

Stack Overflow用户

发布于 2018-08-29 01:27:54

您使用sharp(' stream ')不起作用,因为函数正在寻找一个字符串作为它的输入,并且您正在尝试给它一个流。根据文档,您需要从readableStream中读取数据,然后处理图像。

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

希望得到帮助!

代码语言:javascript
复制
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');
    }
});
票数 1
EN

Stack Overflow用户

发布于 2018-11-20 06:44:58

在我的案例中,我使用了Sharp的如下方式,这是非常好的。

代码语言:javascript
复制
            sharp('stream')
            .png()
            .resize(100, 100)
            .toBuffer((err, buffer, info) => {
                if (err)
                    console.log(err);

                if (buffer) {
                    return buffer;
                }
            });

夏普的toFile()将输出保存在文件中,因此可以将文件名作为参数。toBuffer()将返回一个缓冲对象。希望能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51983346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档