PGMLoader.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. if (context.type == PGMLoadingContext::Type::ASCII) {
  31. while (true) {
  32. auto number_or_error = read_number(streamer);
  33. if (number_or_error.is_error())
  34. break;
  35. auto value = number_or_error.value();
  36. if (read_whitespace(context, streamer).is_error())
  37. break;
  38. color_data.append({ (u8)value, (u8)value, (u8)value });
  39. }
  40. } else if (context.type == PGMLoadingContext::Type::RAWBITS) {
  41. u8 pixel;
  42. while (streamer.read(pixel)) {
  43. color_data.append({ pixel, pixel, pixel });
  44. }
  45. }
  46. size_t context_size = (u32)context.width * (u32)context.height;
  47. if (context_size != color_data.size()) {
  48. dbgln("Not enough color data in image.");
  49. return false;
  50. }
  51. if (!create_bitmap(context))
  52. return false;
  53. set_adjusted_pixels(context, color_data);
  54. context.state = PGMLoadingContext::State::Bitmap;
  55. return true;
  56. }
  57. }