简体   繁体   中英

Invalid file signature in JIMP in nodejs

I am using JIMP to convert my image to greyscale and to reduce its quality.But for 2% of the cases it is corrupting my image and throwing an error in the console- "Error: Invalid file signature at Parser._parseSignature (C:\\Users\\Akshay\\Desktop\\darwin\\node_modules\\pngjs \\lib\\parser.js:50:18)" Below if the problematic code:

 var ext=path.extname(dest);
      if(ext!='.jpg'){
       dest=replaceExt(dest, '.jpg');
      }
      console.log(path.extname(dest));
      var file = fs.createWriteStream(dest);
      ////console.log(url)
      if(url.indexOf('https')!=-1){
        //console.log("https")
        var request = https.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
          Jimp.read(dest).then(function (lennaa) {
            lennaa.resize(256, 256)            // resize
              .quality(90)                 // set JPEG quality
              .greyscale()                 // set greyscale
              .write(dest); // save
          }).catch(function (err) {
            console.error(err);
          });
          file.close(cb);  // close() is async, call cb after close completes.
        });
      }).on('error', function(err) { // Handle errors
        fs.unlink(dest); // Delete the file async. (But we don't check the result)
        if (cb) cb(err.message);
      });
      }

I faced the same and it seems that the issue is that the previous file is still not finished writing, despite our best effort.

So I did it in a dumb, shameful way and added a half-second delay in case the read fails.

let image;
try {
  image = await Jimp.read(filepath);
} catch (error) {
  debug(`Error reading ${filepath}. But we'll try again!`);

  // Wait half second, try again. What an ugly hack. It might as well work.
  let temp = await new Promise(resolve => setTimeout(resolve, 600));
  try {
    image = await Jimp.read(filepath);
    debug('Success reading file on second attempt!');
  } catch (error2) {
    // If totally failed, at least exit gracefully:
    this.session.send('The bot is a little busy now. Please try again.');
    this.session.endDialog();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM