Download image and resize in nodejs

随声附和 提交于 2021-01-29 17:50:33

问题


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);
        }   

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.

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.


回答1:


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);
});


来源:https://stackoverflow.com/questions/56765028/download-image-and-resize-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!