下载图像并在Node.js中调整大小 [英] Download image and resize in nodejs

查看:96
本文介绍了下载图像并在Node.js中调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是将图像从Google下载到项目文件夹/download 中的系统存储库中.接下来,我尝试从 download 存储库中获取图像并调整大小,然后将调整大小后的图像再次保存在/thumbnail 存储库中.下面是我编写的代码

What I am trying to do is download an image from google into my system repository in the project folder /download. Next, I am trying to get the image from the download repository and resize and again save the resized image in /thumbnail repository. Below is the code which I have written

     //Google URL
     var mainuri = 'http://images.sadhguru.org/sites/default/files/media_files/iso/en/64083-natures-temples.jpg';
            var dir = './download';

        if (!fs.existsSync(dir)){
            fs.mkdirSync(dir);
        }
      // CODE TO DOWNLOAD IMAGE FROM GOOGLE 
        var filename = dir+'/file.jpg';
            request.head(mainuri, function(err, res, body){
              console.log('content-type:', res.headers['content-type']);
              console.log('content-length:', res.headers['content-length']);

              request(mainuri).pipe(fs.createWriteStream(filename));
            });


            var resizedir = './thumbnail';

            if (!fs.existsSync(resizedir)){
                fs.mkdirSync(resizedir);
            }

      //CODE TO GET IMAGE FROM '/download' REPOSITORY AND RESIZE
            var inputFile=require('path').join(__dirname,'../download/file.jpg'); //GET IMAGE FROM LOCAL
            var outFile = 'thumbnail/newfile.jpg'; // SAVE RESIZED IMAGE PATH 

// ------- CODE REMOVED - ERROR IS COMING HERE -----------

           imageresize(inputFile, outFile); // FUNCTION THAT CONTAINS IMAGE RESIZE CODE 

//imageresize FUNCTION

            var imageresize = function(inputFile, outFile){
            console.log(inputFile)
            // input stream
            let inStream = fs.createReadStream('C:/Users/rganji/caw/server/download/file.jpg');

            // output stream
            let outStream = fs.createWriteStream(outFile, {flags: "w"});

            // on error of output file being saved
            outStream.on('error', function() {
                console.log("Error");
            });

            // on success of output file being saved
            outStream.on('close', function() {
                console.log("Successfully saved file");
            });

            // input stream transformer
            // "info" event will be emitted on resize
            let transform = sharp()
                                .resize({ width: 50, height: 50 })
                                .on('info', function(fileInfo) {
                                    console.log("Resizing done, file not saved");
                                });

            inStream.pipe(transform).pipe(outStream);
        }   

如果我删除了注释为代码已删除-此处出现错误"的代码,则表示正在从Google下载图片.如果我调用 imageresize 函数,则会创建/download 目录,但是我无法在该目录中找到任何图像.

If I remove the code which I commented as CODE REMOVED - ERROR IS COMING HERE, then image is getting downloaded from google. If I call imageresize function then the /download directory is getting created but I couldnt find any image in the directory.

即,如果我分别调用从google的下载和resizeimage函数,即先调用google的图像下载,然后再调用imageresize,则它们工作正常,即我可以在/download /thumbnail 目录.但是,如果我在Google下载后调用resizeimage函数,那么我在两个存储库中都找不到任何图像.

i.e, If I call the download from google and resizeimage functions separately, i.e calling image download from google first and imageresize next then they are working fine that is I can find images in both /download and /thumbnail directories. But If I call resizeimage function after google download then I couldnt find any image in both the repositories.

推荐答案

在调用 imageresize 函数之前,您需要等待图像下载完成.试试这个

You need to wait for the image download to get finished before calling the imageresize function. Try this

request(mainuri).on('end', function() {
    var inputFile=require('path').join(__dirname,'../download/file.jpg'); //GET IMAGE FROM LOCAL
    var outFile = 'thumbnail/newfile.jpg'; // SAVE RESIZED IMAGE PATH 
    imageresize(inputFile, outFile);
});

这篇关于下载图像并在Node.js中调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆