1 /*
2 * Copyright 2024 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/core/SkCanvas.h"
9 #include "include/core/SkStream.h"
10 #include "include/core/SkSurface.h"
11 #include "include/encode/SkPngEncoder.h"
12 #include "modules/skottie/include/Skottie.h"
13
14 #include <cstdio>
15
main(int argc,char ** argv)16 int main(int argc, char** argv) {
17 if (argc != 2 && argc != 3) {
18 std::printf("Usage: %s <lottie.json> [<nframes>]", argv[0]);
19 return 1;
20 }
21 SkFILEStream input(argv[1]);
22 if (!input.isValid()) {
23 std::printf("Cannot open input file %s\n", argv[1]);
24 return 1;
25 }
26
27 unsigned n = 1;
28 if (argc == 3) {
29 if (1 != std::sscanf(argv[2], "%u", &n)) {
30 std::printf("Usage: %s <lottie.json> [<nframes>]", argv[0]);
31 return 1;
32 }
33 }
34
35 auto animation = skottie::Animation::Make(&input);
36 if (!animation) {
37 std::printf("Cannot parse input file %s\n", argv[1]);
38 return 1;
39 }
40 SkISize surfaceSize = animation->size().toCeil();
41 auto surface = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(surfaceSize, nullptr));
42 if (!surface) {
43 std::printf("Cannot allocate surface of size %d x %d\n",
44 surfaceSize.width(),
45 surfaceSize.height());
46 return 1;
47 }
48
49 for (unsigned f = 0; f < n; ++f) {
50 double t;
51 SkString outFileName;
52 if (n > 1) {
53 t = static_cast<double>(f) / (n - 1) * animation->duration();
54 outFileName = SkStringPrintf("%s.%u.png", argv[1], f);
55 } else {
56 t = 0.0;
57 outFileName = SkStringPrintf("%s.png", argv[1]);
58 }
59 surface->getCanvas()->clear(SK_ColorWHITE);
60 animation->seekFrameTime(t);
61 animation->render(surface->getCanvas());
62
63 SkFILEWStream out(outFileName.c_str());
64 if (!out.isValid()) {
65 std::printf("Cannot open output file %s\n", outFileName.c_str());
66 return 1;
67 }
68
69 if (SkPixmap pm; !surface->peekPixels(&pm) || !SkPngEncoder::Encode(&out, pm, {})) {
70 std::printf("Cannot encode rendering to PNG.\n");
71 return 1;
72 }
73 }
74 return 0;
75 }
76