createGifFromVideo method
Implementation
Future<Uint8List> createGifFromVideo(
XFile videoFile, {
int fps = 1,
int? width,
int? height,
bool forceOriginalAspectRatio = true,
List<GifyTextMessage>? textMessages,
}) async {
final tempDir = await getTemporaryDirectory();
// REF: https://github.dev/arthenica/ffmpeg-kit-test/blob/ce66bf7c1ab2978579405d0a5b06f38936c0893f/flutter/test-app-pub/lib/video_util.dart#L46-L48
await FFmpegKitConfig.setFontDirectoryList(
[tempDir.path, "/system/fonts", "/System/Library/Fonts"], {});
const fontName = 'Roboto Bold';
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
final textMessagesCommand = textMessages == null
? ''
: ',${textMessages.map((message) => 'drawtext=font=\'$fontName\':fontsize=${message.fontSize}:fontcolor=0x${message.fontColor.toHex()}:text="${message.text}":x=${message.x}:y=${message.y}').join(',')}';
final String framesCommand =
'-i ${videoFile.path} -vf scale=w=${width ?? -1}:h=${height ?? -1}${forceOriginalAspectRatio ? ':force_original_aspect_ratio=decrease' : ''}$textMessagesCommand -r $fps -f image2 ${tempDir.path}/${videoFile.name}-$currentTime-%3d.png';
final framesSession = await FFmpegKit.execute(framesCommand);
final framesReturnCode = await framesSession.getReturnCode();
if (!ReturnCode.isSuccess(framesReturnCode)) {
return Uint8List.fromList([]);
}
final String gifCommand =
'-f image2 -r $fps -i ${tempDir.path}/${videoFile.name}-$currentTime-%3d.png -loop 0 ${tempDir.path}/${videoFile.name}_$currentTime.gif';
final gifSession = await FFmpegKit.execute(gifCommand);
final gifReturnCode = await gifSession.getReturnCode();
if (!ReturnCode.isSuccess(gifReturnCode)) {
return Uint8List.fromList([]);
}
final result =
await File('${tempDir.path}/${videoFile.name}_$currentTime.gif')
.readAsBytes();
return result;
}