【问题标题】:Imagemin in Electron App Not Compressing ImagesElectron App中的Imagemin不压缩图像
【发布时间】:2020-12-30 15:52:18
【问题描述】:

我正在尝试使用此代码在 Electron 应用程序中压缩单个 PNG 图像

  const files = await imagemin([filePath], {
    destination: destinationPath,
    plugins: [
      imageminPngquant({
        quality: [0.2, 0.4],
        speed: 1
      })
    ]
  });
  debuglog(files);

filePath 包含一个 PNG 文件的完整路径,例如

C:\Users\name\Downloads\images\needle.png

此文件确实存在,并且路径正确:当我将相同的路径放入 Windows 资源管理器时,png 会打开。

destinationPath 包含指向 .png 文件所在目录的路径(换句话说,我想覆盖原始文件),例如

C:\Users\name\Downloads\images

当我运行这个时,原始文件保持不变,函数调用返回的变量“files”包含一个空数组。

我做错了什么?有没有办法让调试输出告诉我 imagemin 到底在做什么?

更新:这是一个具体的例子。代码如下所示:

  console.log("compressPNG");
  console.log(filePath);
  console.log(path);
  var files = await imagemin([filePath], {
    destination: path,
    plugins: [
      imageminPngquant({
        quality: [0.2, 0.4],
        speed: 1
      })
    ]
  });
  console.log(files);

这会产生以下日志输出:

【问题讨论】:

  • 你能console.log()你发布的代码之前的两条路径吗?反斜杠可能是个问题。
  • 另外,对于将来,在您的帖子中包含 minimal reproducible example 会很有帮助。到目前为止,我根本看不到与 Electron 的联系,所以这个例子可能非常简洁。尽管如此,让帮助他们尽可能容易(并且通常会阻止提出整个问题)是 OP 工作的一部分。
  • 谢谢你,snwflk,我添加了一个示例,显示路径的实际日志输出。我不确定如何创建一个可重现的 Electron 应用程序示例,也不确定是否有与 Electron 的连接,但由于它发生在 Electron 应用程序中,我认为我应该提供该上下文。我会尝试想出一些我可以发布的可重现的东西。

标签: node.js electron imagemin


【解决方案1】:

This bug report 表示需要将反斜杠(\)转换为正斜杠(/)。

根据其中一位评论者的说法,imagemin 所依赖的包 globby 需要使用正斜杠 (/) 作为分隔符的文件路径。

这是一个完整的例子:

const imagemin = require("imagemin");
const imageminPngquant = require("imagemin-pngquant");

let input_path = "C:\\path\\to\\file.png";
let output_dir = "C:\\output\\directory";

// Replace backward slashes with forward slashes      <-- Option A
input_path = input_path.replace(/\\/g, "/");
output_dir = output_dir.replace(/\\/g, "/");

(async () => {
  var files = await imagemin([input_path], {
    destination: output_dir,
    // glob: false,                                   <-- Option B
    plugins: [
      imageminPngquant({
        quality: [0.2, 0.4],
        speed: 1
      })
    ]
  });
  console.log(files);
})();

另外,设置 glob: false 也应该有助于接受 Windows 文件路径,因为它绕过了 globby 模块的使用。

【讨论】:

  • 成功了!太感谢你了,我快疯了。
猜你喜欢
  • 2023-04-06
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
相关资源
最近更新 更多