Serenity Operating System
at master 62 lines 2.3 kB view raw
1/* 2 * Copyright (c) 2023, Nico Weber <thakis@chromium.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <LibCore/ArgsParser.h> 8#include <LibCore/File.h> 9#include <LibCore/MappedFile.h> 10#include <LibGfx/BMPWriter.h> 11#include <LibGfx/ImageDecoder.h> 12#include <LibGfx/PNGWriter.h> 13#include <LibGfx/PortableFormatWriter.h> 14#include <LibGfx/QOIWriter.h> 15 16ErrorOr<int> serenity_main(Main::Arguments arguments) 17{ 18 Core::ArgsParser args_parser; 19 20 StringView in_path; 21 args_parser.add_positional_argument(in_path, "Path to input image file", "FILE"); 22 23 StringView out_path; 24 args_parser.add_option(out_path, "Path to output image file", "output", 'o', "FILE"); 25 26 bool ppm_ascii; 27 args_parser.add_option(ppm_ascii, "Convert to a PPM in ASCII", "ppm-ascii", {}); 28 29 args_parser.parse(arguments); 30 31 if (out_path.is_empty()) { 32 warnln("-o is required"); 33 return 1; 34 } 35 36 auto file = TRY(Core::MappedFile::map(in_path)); 37 auto decoder = Gfx::ImageDecoder::try_create_for_raw_bytes(file->bytes()); 38 39 // This uses ImageDecoder instead of Bitmap::load_from_file() to have more control 40 // over selecting a frame, access color profile data, and so on in the future. 41 auto frame = TRY(decoder->frame(0)).image; 42 43 ByteBuffer bytes; 44 if (out_path.ends_with(".bmp"sv, CaseSensitivity::CaseInsensitive)) { 45 bytes = TRY(Gfx::BMPWriter::encode(*frame)); 46 } else if (out_path.ends_with(".png"sv, CaseSensitivity::CaseInsensitive)) { 47 bytes = TRY(Gfx::PNGWriter::encode(*frame)); 48 } else if (out_path.ends_with(".ppm"sv, CaseSensitivity::CaseInsensitive)) { 49 auto const format = ppm_ascii ? Gfx::PortableFormatWriter::Options::Format::ASCII : Gfx::PortableFormatWriter::Options::Format::Raw; 50 bytes = TRY(Gfx::PortableFormatWriter::encode(*frame, Gfx::PortableFormatWriter::Options { .format = format })); 51 } else if (out_path.ends_with(".qoi"sv, CaseSensitivity::CaseInsensitive)) { 52 bytes = TRY(Gfx::QOIWriter::encode(*frame)); 53 } else { 54 warnln("can only write .bmp, .png, .ppm, and .qoi"); 55 return 1; 56 } 57 58 auto output_stream = TRY(Core::File::open(out_path, Core::File::OpenMode::Write)); 59 TRY(output_stream->write_until_depleted(bytes)); 60 61 return 0; 62}