PGMLoader.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 <AK/Endian.h>
  8. #include <LibGfx/ImageFormats/PGMLoader.h>
  9. #include <LibGfx/ImageFormats/PortableImageLoaderCommon.h>
  10. #include <LibGfx/Streamer.h>
  11. #include <string.h>
  12. namespace Gfx {
  13. static void set_adjusted_pixels(PGMLoadingContext& context, Vector<Gfx::Color> const& color_data)
  14. {
  15. size_t index = 0;
  16. for (size_t y = 0; y < context.height; ++y) {
  17. for (size_t x = 0; x < context.width; ++x) {
  18. Color color = color_data.at(index);
  19. if (context.format_details.max_val < 255) {
  20. color = adjust_color(context.format_details.max_val, color);
  21. }
  22. context.bitmap->set_pixel(x, y, color);
  23. ++index;
  24. }
  25. }
  26. }
  27. bool read_image_data(PGMLoadingContext& context, Streamer& streamer)
  28. {
  29. Vector<Gfx::Color> color_data;
  30. auto const context_size = context.width * context.height;
  31. color_data.resize(context_size);
  32. if (context.type == PGMLoadingContext::Type::ASCII) {
  33. for (u64 i = 0; i < context_size; ++i) {
  34. auto number_or_error = read_number(streamer);
  35. if (number_or_error.is_error())
  36. return false;
  37. auto value = number_or_error.value();
  38. if (read_whitespace(context, streamer).is_error())
  39. return false;
  40. color_data[i] = { (u8)value, (u8)value, (u8)value };
  41. }
  42. } else if (context.type == PGMLoadingContext::Type::RAWBITS) {
  43. for (u64 i = 0; i < context_size; ++i) {
  44. u8 pixel;
  45. if (!streamer.read(pixel))
  46. return false;
  47. color_data[i] = { pixel, pixel, pixel };
  48. }
  49. }
  50. if (!create_bitmap(context))
  51. return false;
  52. set_adjusted_pixels(context, color_data);
  53. context.state = PGMLoadingContext::State::Bitmap;
  54. return true;
  55. }
  56. }