How can I extract the first frame of a GIF and save it as a PNG using GraphicsMagick on NodeJS?

本秂侑毒 提交于 2019-12-06 13:32:49
Lucio Mollinedo

I don't know why this isn't in the documentation, but someone else answered this here on stackoverflow.

So, you can use this either with a file path string or a stream/buffer, like so:

For a file:

gm('/path/to/animated.gif')
.selectFrame(0)
.write('/path/to/firstframe.png', function(err){
    if (err) print('  :(  ');
})

For a stream/buffer:

gm(streamOrBuffer)
.selectFrame(0)
.write('/path/to/firstframe.png', function(err){
    if (err) print('  :(  ');
})

In the documentation they say you need to change the path string to be something like '/path/to/animated.gif[0]' to be more specific with the frame you want to select, but I tested that code without specifying the frame, and it worked fine (using gm@1.21.1 and ImageMagick 6.7.7-10 2014-03-06). Also, what they had in the documentation (without using selectFrame) didn't work. It ended up crashing and creating several png frames of the whole gif in the process.

Why they haven't documented selectFrame yet is beyond me. As they pointed out in the cited link, there's an open issue wondering precisely that.

Since I couldn't get it working on the server-side, I ended up just drawing the .gif to a <canvas> element to "simulate" extracting a .gif's first frame. This gave me the paused gif that I was going for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!