node 图片压缩采坑小记.md

前言

由于有需要在electron平台上做图片压缩,系统要求为win8.1和macOS,因此有了这篇文章。对于macOS各种库基本没问题,本文主要讲的是window下electron相关的native module的安装过程,包括其中碰到的问题。

使用平台

  • node 6.7.3
  • electron 1.6.6
  • mac os 12.13.6、 win8.1

第三方库

node-images (windows未成功)

直接下载npm install images, 库会根据不同的node平台下载编译好的.node文件,但是由于我是希望在electron平台下使用,因此需要自己重新编译,最后一步node-gyp rebuild --runtime=electron --target_arch=ia32 --target=1.6.6 --disturl=https://atom.io/download/atom-shell,编译为electron能使用的包

  $ git clone https://github.com/zhangyuanwei/node-images
  $ cd node-images
  $ git submodule init
  $ git submodule update
  $ cd gyp
  $ sh third-party.sh
  $ cd ..
  $ npm install
  $ node-gyp rebuild

碰到问题:
- giflib, 'not found unistd.h'
解决办法: 删除unistd.h,windows下不需要引入这个h头文件

  • 后续又报了一个c++的错,看起来像是libjpeg-turbo第三方库, 但是这些库作者自己引入的并做了修改,排查后没找到好的解决方法,window平台重新编译都没通过,看了代码 和node-canvas类似,引入的库文件也是libjpeg-turbo、png等图形库

node-canvas

1.x 版本不支持jpeg转换 lib需要换到2.0版本
因为需要重新打包为32位的electron版本,对应库文件需要安装32位的,libjpeg-turbo、GTK,否则重新编译node文件的时候就会报错

安装过程:

  • choco install -y python2 gtk-runtime microsoft-build-tools libjpeg-turbo (may require sudo/Administrator).
  • You will need the cairo library which is bundled in GTK. Download the GTK 2 bundle for Win32 or Win64. Unzip the contents in C:\GTK.
  • npm install canvas or yarn add node-canvas.
  • node-gyp rebuild --runtime=electron --target_arch=ia32 --target=1.2.6 --disturl=https://atom.io/download/atom-shell

碰到问题:

  • canvas[method] is not function
    因为1.x版本不支持jpeg转换。libjpeg-turbo没有被链接到node文件中 issue770
    解决方法:切换到2.x版本
  • the specified module could not be found
    因为缺少一些dll文件, 在我自己的window电脑上很好用,结果换了一台电脑,提示上述的错误
    解决方法: 使用depends.exe,将node文件放进去,看两者之间缺少那些dll,然后找32位的dll放到node文件中

  • %1 is not a valid Win32 application
    因为引用了一些不兼容的dll库文件

  • node-canvas 如何输出流?
  let buffers = [];
  canvas.createJPEGStream({
    quality: 80,
  }).on('data', function(data) {
    console.log('rcvd', data.length); // <-- this always prints 4096, even for the last buffer!
    buffers.push(data);
  }).on('end', function() {
    // fs.writeFileSync(path.join(app.getPath('userData'), './out.jpeg'), Buffer.concat(buffers));
    uploadPic(Buffer.concat(buffers));
  }).on('error', function(err) {
    console.log(err);
  });
  • windows 提示out of memory。
    一度放弃….后来发现可能是因为大图片electron同时显示和操作的原因。

    解决方法:把源文件输入到一个压缩后的文件,显示的时候显示压缩文件,传输的时候传输源文件

  • 加了队列之后 重发的情况,大图不显示出来了???

    扫描二维码关注公众号,回复: 474400 查看本文章

    解决方法:先显示出来,再进队列

  • 打包前是好的,打包后图片压缩有问题

    解决方法:将node-canvas库文件放到外部,拷贝进去,不打包到app.asar中

猜你喜欢

转载自blog.csdn.net/lihangxiaoji/article/details/79959751