【问题标题】:NodeJS and Sharp, BMP to PNG Error: Input file contains unsupported image formatNodeJS 和 Sharp,BMP 到 PNG 错误:输入文件包含不受支持的图像格式
【发布时间】:2019-10-10 20:58:18
【问题描述】:

我正在使用清晰的服务器端来准备要在 web 应用程序中提供的图片。 当前目标是加载图片(BMP 格式),将其加载到 nodejs 中,将其转换为 PNG,调整其大小(按比例缩小)并将其保存回磁盘。代码如下:

  if(resize_pictures){

      (...)

      console.log('Reducing image size ... ');
      fs.readdirSync(input_folder).forEach(file => {
            tmp_input_path = path.join(input_folder, file)
            tmp_output_path = path.join(tmp_folder_reduced, file)

            //Resize
            sharp(tmp_input_path)
                .png() // Convert to png
                .resize(target_width,null)
                .flatten()
                .toFile(tmp_output_path,
                function(err){
                    if(err){
                    console.log("Error at reducing size / converting picture : ")
                    console.log(err)
                    console.log(tmp_input_path);
                    console.log(tmp_output_path);
                    return;
                    }
                })
    })
    console.log('Image reduction completed.');

我收到了这个错误:

Reducing image size ... 
Image reduction completed.
Error at reducing size / converting picture : 
[Error: Input file contains unsupported image format]
/home/user/<folder>/16c93ac9f297376b1b44eeeecff141b1f59a239d.bmp
/home/user/<folder>/TMP/16c93ac9f297376b1b44eeeecff141b1f59a239d.bmp

输出文件夹保持为空。

我真的不明白为什么:路径是正确的,因此可以访问。图片存储在磁盘上,路径直接在服务器端计算(所以没有编码问题,因为我可能在其他地方看到过这个问题)。

有人有想法或解决方案吗?

【问题讨论】:

    标签: javascript node.js png bmp sharp


    【解决方案1】:

    好像sharp不能处理BMP图片。 (见:https://github.com/lovell/sharp/issues/1255

    所以我改用 Jimp(请参阅:https://www.npmjs.com/package/jimp):

      console.log('Reducing image size ... ');
      fs.readdirSync(input_folder).forEach(file => {
            let tmp_input_path = path.join(input_folder, file)
            let tmp_file = file.substr(0, file.lastIndexOf(".")) + ".png";
            let tmp_output_path = path.join(tmp_folder_reduced, tmp_file)
    
            if(fs.existsSync(tmp_input_path)){
                console.log("File exist ! ")
            }
    
            //Resize
            Jimp.read(tmp_input_path)
                .then(image => {
                    image
                    .resize(target_width, Jimp.AUTO)
                    .write(tmp_output_path)
                })
                .catch(err => {
                    console.log("Error at reducing size / converting picture : ")
                    console.log(err)
                    console.log(tmp_input_path);
                    console.log(tmp_output_path);
                });
    

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2023-04-03
      • 2020-03-03
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 2014-06-29
      • 2016-07-28
      相关资源
      最近更新 更多