image.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2023, 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/BMPWriter.h>
  10. #include <LibGfx/ImageDecoder.h>
  11. #include <LibGfx/PNGWriter.h>
  12. #include <LibGfx/PortableFormatWriter.h>
  13. #include <LibGfx/QOIWriter.h>
  14. ErrorOr<int> serenity_main(Main::Arguments arguments)
  15. {
  16. Core::ArgsParser args_parser;
  17. StringView in_path;
  18. args_parser.add_positional_argument(in_path, "Path to input image file", "FILE");
  19. StringView out_path;
  20. args_parser.add_option(out_path, "Path to output image file", "output", 'o', "FILE");
  21. bool ppm_ascii;
  22. args_parser.add_option(ppm_ascii, "Convert to a PPM in ASCII", "ppm-ascii", {});
  23. args_parser.parse(arguments);
  24. if (out_path.is_empty()) {
  25. warnln("-o is required");
  26. return 1;
  27. }
  28. auto file = TRY(Core::MappedFile::map(in_path));
  29. auto decoder = Gfx::ImageDecoder::try_create_for_raw_bytes(file->bytes());
  30. // This uses ImageDecoder instead of Bitmap::load_from_file() to have more control
  31. // over selecting a frame, access color profile data, and so on in the future.
  32. auto frame = TRY(decoder->frame(0)).image;
  33. ByteBuffer bytes;
  34. if (out_path.ends_with(".bmp"sv, CaseSensitivity::CaseInsensitive)) {
  35. bytes = TRY(Gfx::BMPWriter::encode(*frame));
  36. } else if (out_path.ends_with(".png"sv, CaseSensitivity::CaseInsensitive)) {
  37. bytes = TRY(Gfx::PNGWriter::encode(*frame));
  38. } else if (out_path.ends_with(".ppm"sv, CaseSensitivity::CaseInsensitive)) {
  39. auto const format = ppm_ascii ? Gfx::PortableFormatWriter::Options::Format::ASCII : Gfx::PortableFormatWriter::Options::Format::Raw;
  40. bytes = TRY(Gfx::PortableFormatWriter::encode(*frame, Gfx::PortableFormatWriter::Options { .format = format }));
  41. } else if (out_path.ends_with(".qoi"sv, CaseSensitivity::CaseInsensitive)) {
  42. bytes = TRY(Gfx::QOIWriter::encode(*frame));
  43. } else {
  44. warnln("can only write .bmp, .png, .ppm, and .qoi");
  45. return 1;
  46. }
  47. auto output_stream = TRY(Core::File::open(out_path, Core::File::OpenMode::Write));
  48. TRY(output_stream->write_until_depleted(bytes));
  49. return 0;
  50. }