nodejs中JIMP中的文件签名无效

时间:2017-09-25 11:27:51

标签: javascript node.js image-processing npm

我正在使用JIMP将我的图像转换为灰度并降低其质量。但是对于2%的情况,它会破坏我的图像并在控制台中抛出错误 - “错误:文件签名无效     在Parser._parseSignature(C:\ Users \ Akshay \ Desktop \ darwin \ node_modules \ pngjs \ lib中\ parser.js:50:18)” 如果有问题的代码如下:

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

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,似乎问题在于,尽管我们付出了最大的努力,但之前的文件仍然没有写完。

所以我是以一种愚蠢,可耻的方式做到这一点,并在读取失败的情况下增加了半秒延迟。

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