PortableFormatWriter.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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/FixedArray.h>
  8. #include <AK/Stream.h>
  9. namespace Gfx {
  10. ErrorOr<void> PortableFormatWriter::encode(Stream& output, Bitmap const& bitmap, Options options)
  11. {
  12. // FIXME: Add support for PBM and PGM
  13. TRY(add_header(output, options, bitmap.width(), bitmap.height(), 255));
  14. TRY(add_pixels(output, options, bitmap));
  15. return {};
  16. }
  17. ErrorOr<void> PortableFormatWriter::add_header(Stream& output, Options const& options, u32 width, u32 height, u32 maximal_value)
  18. {
  19. TRY(output.write_formatted("P{}\n", options.format == Options::Format::ASCII ? "3"sv : "6"sv));
  20. TRY(output.write_formatted("# {}\n", options.comment));
  21. TRY(output.write_formatted("{} {}\n", width, height));
  22. TRY(output.write_formatted("{}\n", maximal_value));
  23. return {};
  24. }
  25. ErrorOr<void> PortableFormatWriter::add_pixels(Stream& output, Options const& options, Bitmap const& bitmap)
  26. {
  27. if (options.format == Options::Format::Raw) {
  28. auto row = TRY(FixedArray<u8>::create(bitmap.width() * 3ul));
  29. for (int i = 0; i < bitmap.height(); ++i) {
  30. for (int j = 0; j < bitmap.width(); ++j) {
  31. auto const color = bitmap.get_pixel(j, i);
  32. row.unchecked_at(j * 3 + 0) = color.red();
  33. row.unchecked_at(j * 3 + 1) = color.green();
  34. row.unchecked_at(j * 3 + 2) = color.blue();
  35. }
  36. TRY(output.write_until_depleted(row.span()));
  37. }
  38. return {};
  39. }
  40. for (int i = 0; i < bitmap.height(); ++i) {
  41. for (int j = 0; j < bitmap.width(); ++j) {
  42. auto color = bitmap.get_pixel(j, i);
  43. TRY(output.write_formatted("{} {} {}\t", color.red(), color.green(), color.blue()));
  44. }
  45. TRY(output.write_value('\n'));
  46. }
  47. return {};
  48. }
  49. }