PortableFormatWriter.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org >
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "PortableFormatWriter.h"
  7. #include <AK/String.h>
  8. namespace Gfx {
  9. ErrorOr<ByteBuffer> PortableFormatWriter::encode(Bitmap const& bitmap, Options options)
  10. {
  11. ByteBuffer buffer;
  12. // FIXME: Add support for PBM and PGM
  13. TRY(add_header(buffer, options, bitmap.width(), bitmap.height(), 255));
  14. TRY(add_pixels(buffer, options, bitmap));
  15. return buffer;
  16. }
  17. ErrorOr<void> PortableFormatWriter::add_header(ByteBuffer& buffer, Options const& options, u32 width, u32 height, u32 maximal_value)
  18. {
  19. TRY(buffer.try_append(TRY(String::formatted("P{}\n", options.format == Options::Format::ASCII ? "3"sv : "6"sv)).bytes()));
  20. TRY(buffer.try_append(TRY(String::formatted("# {}\n", options.comment)).bytes()));
  21. TRY(buffer.try_append(TRY(String::formatted("{} {}\n", width, height)).bytes()));
  22. TRY(buffer.try_append(TRY(String::formatted("{}\n", maximal_value)).bytes()));
  23. return {};
  24. }
  25. ErrorOr<void> PortableFormatWriter::add_pixels(ByteBuffer& buffer, Options const& options, Bitmap const& bitmap)
  26. {
  27. for (int i = 0; i < bitmap.height(); ++i) {
  28. for (int j = 0; j < bitmap.width(); ++j) {
  29. auto color = bitmap.get_pixel(j, i);
  30. if (options.format == Options::Format::ASCII) {
  31. TRY(buffer.try_append(TRY(String::formatted("{} {} {}\t", color.red(), color.green(), color.blue())).bytes()));
  32. } else {
  33. TRY(buffer.try_append(color.red()));
  34. TRY(buffer.try_append(color.green()));
  35. TRY(buffer.try_append(color.blue()));
  36. }
  37. }
  38. if (options.format == Options::Format::ASCII)
  39. TRY(buffer.try_append('\n'));
  40. }
  41. return {};
  42. }
  43. }