通过在代码中调用 Gifsicle 命令将 PNG 转换为动画 Gif

Convert PNG to Animated Gif with calling Gifsicle command in code

在为 Sketch 开发插件时,我需要通过 JavaScript 运行 Gifsicle 命令。正在尝试将 PNG 图像序列转换为动画 GIF。

  1. 首先我创建临时文件夹表格图像(有效)
  2. 然后 运行宁 OSX sips command 进行 PNG 到 GIF 的转换过程并获得单个 GIF 文件(有效)
  3. 然后尝试使用 Gifsicle 命令从文件夹中的单个 GIF 文件制作动画 GIF。我只从 Gifsicle 获得了空的动画 GIF 文件。 (失败)

代码如下:

function convertPngToGif (exportFileName, exportFolder) {

// Create Temporary folder for conversion process
var fileManager = NSFileManager.defaultManager();
var uniqueID = NSProcessInfo.processInfo().globallyUniqueString();
var tmpPathUrl = NSTemporaryDirectory();
var tmpFolder = tmpPathUrl.stringByAppendingPathComponent(uniqueID);
fileManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error(tmpFolder, true, null, null);

// Path to gifsicle
var gifConverter = utils.scriptLibraryPath + "/gifsicle";

// Create bash arguments
var convertGifImages = "find \"" + exportFolder + "\" -name '*.png' -exec sips -s format gif -o \"" + tmpFolder + "\" {}.gif {} \;"
var convertGifAnimation = "find \"" + tmpFolder + "\" -name '*.gif' -execdir bash -c '\"" + gifConverter + "\" --delay=10 '*.gif' > \"" + exportFolder + '/' + exportFileName + '.gif' + "\"' \;"

var convertTask = NSTask.alloc().init();
var createTask = NSTask.alloc().init();

// Create GIF Image Sequence from exist PNG images
convertTask.setLaunchPath("/bin/bash");
convertTask.setArguments(["-c", convertGifImages]);
convertTask.launch();
convertTask.waitUntilExit();

// Create GIF animation from converted images
createTask.setLaunchPath("/bin/bash");
createTask.setArguments(["-c", convertGifAnimation]);
createTask.launch();
createTask.waitUntilExit();

// Remove temporary folder
fileManager.removeItemAtPath_error_(tmpFolder, null);
}

测试时请注意:我已经尝试过 Gifsicle commands。它不会使用输出 '-o' 命令创建该空文件,但使用 '>' 它将创建该空文件。

通过终端工作

我已经通过终端手动尝试了整个命令,因为它出现在函数字符串中并且它正确地创建了动画 GIF:

find "/GifImagesFolder/" -name '*.gif' -exec "/GifSicleFolder/gifsicle" --delay=10 *.gif -o "/OutputFolder/Example.gif" \;

我想这与那个 bash 命令有关,因为它通过终端而不是代码运行。

已有名为 Generate-GIF for Sketch that uses this PNG to Animated GIF workflow and using Gifsicle. I tested it again but it doesn't work neither for me anymore in version Sketch 3.4.2. So I realized that I've using old AppStrore version, because Sketch moved away from AppStore a while ago 的插件。更新到新的 Sketch 3.4.4 版本后一切正常。我不确定这是否是真正的问题,因为我记得我之前已经在 Sketch 中使用过 GIF 导出。

总之,题中有题。很抱歉造成混淆,但如果遇到同样的问题,这可能仍然对某人有所帮助。