From 2298aac1d1276b7decb8ad7fa8c39623a8eef061 Mon Sep 17 00:00:00 2001 From: Nico Weber Date: Thu, 1 Feb 2024 07:30:23 -0500 Subject: [PATCH] image: Only create output file for known extensions Previously `image -o foo.asdf foo.png` would create a 0-byte foo.asdf before complaining that it doesn't know how to write .asdf images. (Lifetimes of temporaries are extended to the end of the full expresion, so this is fine.) --- Userland/Utilities/image.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Userland/Utilities/image.cpp b/Userland/Utilities/image.cpp index 572223509d..f56a94085a 100644 --- a/Userland/Utilities/image.cpp +++ b/Userland/Utilities/image.cpp @@ -129,16 +129,18 @@ static ErrorOr save_image(LoadedImage& image, StringView out_path, bool pp return Error::from_string_view("Can't save CMYK bitmaps yet, convert to RGB first with --convert-to-color-profile"sv); auto& frame = image.bitmap.get>(); - auto output_stream = TRY(Core::File::open(out_path, Core::File::OpenMode::Write)); - auto buffered_stream = TRY(Core::OutputBufferedFile::create(move(output_stream))); + auto stream = [out_path]() -> ErrorOr> { + auto output_stream = TRY(Core::File::open(out_path, Core::File::OpenMode::Write)); + return Core::OutputBufferedFile::create(move(output_stream)); + }; if (out_path.ends_with(".jpg"sv, CaseSensitivity::CaseInsensitive) || out_path.ends_with(".jpeg"sv, CaseSensitivity::CaseInsensitive)) { - TRY(Gfx::JPEGWriter::encode(*buffered_stream, *frame, { .icc_data = image.icc_data, .quality = jpeg_quality })); + TRY(Gfx::JPEGWriter::encode(*TRY(stream()), *frame, { .icc_data = image.icc_data, .quality = jpeg_quality })); return {}; } if (out_path.ends_with(".ppm"sv, CaseSensitivity::CaseInsensitive)) { auto const format = ppm_ascii ? Gfx::PortableFormatWriter::Options::Format::ASCII : Gfx::PortableFormatWriter::Options::Format::Raw; - TRY(Gfx::PortableFormatWriter::encode(*buffered_stream, *frame, { .format = format })); + TRY(Gfx::PortableFormatWriter::encode(*TRY(stream()), *frame, { .format = format })); return {}; } @@ -152,7 +154,7 @@ static ErrorOr save_image(LoadedImage& image, StringView out_path, bool pp } else { return Error::from_string_view("can only write .bmp, .jpg, .png, .ppm, and .qoi"sv); } - TRY(buffered_stream->write_until_depleted(bytes)); + TRY(TRY(stream())->write_until_depleted(bytes)); return {}; }