PGMLoader.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2020, Hüseyin ASLITÜRK <asliturk@hotmail.com>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "PGMLoader.h"
  8. #include "PortableImageLoaderCommon.h"
  9. namespace Gfx {
  10. static void set_adjusted_pixels(PGMLoadingContext& context, Vector<Gfx::Color> const& color_data)
  11. {
  12. size_t index = 0;
  13. for (size_t y = 0; y < context.height; ++y) {
  14. for (size_t x = 0; x < context.width; ++x) {
  15. Color color = color_data.at(index);
  16. if (context.format_details.max_val < 255) {
  17. color = adjust_color(context.format_details.max_val, color);
  18. }
  19. context.bitmap->set_pixel(x, y, color);
  20. ++index;
  21. }
  22. }
  23. }
  24. ErrorOr<void> read_image_data(PGMLoadingContext& context)
  25. {
  26. auto& stream = *context.stream;
  27. Vector<Gfx::Color> color_data;
  28. auto const context_size = context.width * context.height;
  29. color_data.resize(context_size);
  30. if (context.type == PGMLoadingContext::Type::ASCII) {
  31. for (u64 i = 0; i < context_size; ++i) {
  32. auto value = TRY(read_number(stream));
  33. TRY(read_whitespace(context));
  34. color_data[i] = { static_cast<u8>(value), static_cast<u8>(value), static_cast<u8>(value) };
  35. }
  36. } else if (context.type == PGMLoadingContext::Type::RAWBITS) {
  37. for (u64 i = 0; i < context_size; ++i) {
  38. auto const pixel = TRY(stream.read_value<u8>());
  39. color_data[i] = { pixel, pixel, pixel };
  40. }
  41. }
  42. TRY(create_bitmap(context));
  43. set_adjusted_pixels(context, color_data);
  44. context.state = PGMLoadingContext::State::Bitmap;
  45. return {};
  46. }
  47. }