animation.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2024, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/ArgsParser.h>
  7. #include <LibCore/File.h>
  8. #include <LibCore/MappedFile.h>
  9. #include <LibGfx/ImageFormats/AnimationWriter.h>
  10. #include <LibGfx/ImageFormats/ImageDecoder.h>
  11. #include <LibGfx/ImageFormats/WebPWriter.h>
  12. struct Options {
  13. StringView in_path;
  14. StringView out_path;
  15. bool write_full_frames { false };
  16. };
  17. static ErrorOr<Options> parse_options(Main::Arguments arguments)
  18. {
  19. Options options;
  20. Core::ArgsParser args_parser;
  21. args_parser.add_positional_argument(options.in_path, "Path to input image file", "FILE");
  22. args_parser.add_option(options.out_path, "Path to output image file", "output", 'o', "FILE");
  23. args_parser.add_option(options.write_full_frames, "Do not store incremental frames. Produces larger files.", "write-full-frames");
  24. args_parser.parse(arguments);
  25. if (options.out_path.is_empty())
  26. return Error::from_string_literal("-o is required ");
  27. return options;
  28. }
  29. ErrorOr<int> serenity_main(Main::Arguments arguments)
  30. {
  31. Options options = TRY(parse_options(arguments));
  32. // FIXME: Allow multiple single frames as input too, and allow manually setting their duration.
  33. auto file = TRY(Core::MappedFile::map(options.in_path));
  34. auto decoder = TRY(Gfx::ImageDecoder::try_create_for_raw_bytes(file->bytes()));
  35. if (!decoder)
  36. return Error::from_string_literal("Could not find decoder for input file");
  37. auto output_file = TRY(Core::File::open(options.out_path, Core::File::OpenMode::Write));
  38. auto output_stream = TRY(Core::OutputBufferedFile::create(move(output_file)));
  39. auto animation_writer = TRY([&]() -> ErrorOr<NonnullOwnPtr<Gfx::AnimationWriter>> {
  40. if (options.out_path.ends_with(".webp"sv))
  41. return Gfx::WebPWriter::start_encoding_animation(*output_stream, decoder->size(), decoder->loop_count());
  42. return Error::from_string_literal("Unable to find a encoder for the requested extension.");
  43. }());
  44. RefPtr<Gfx::Bitmap> last_frame;
  45. for (size_t i = 0; i < decoder->frame_count(); ++i) {
  46. auto frame = TRY(decoder->frame(i));
  47. if (options.write_full_frames) {
  48. TRY(animation_writer->add_frame(*frame.image, frame.duration));
  49. } else {
  50. TRY(animation_writer->add_frame_relative_to_last_frame(*frame.image, frame.duration, last_frame));
  51. last_frame = frame.image;
  52. }
  53. }
  54. return 0;
  55. }