PGMLoader.cpp 1.8 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. u16 value;
  32. while (true) {
  33. if (!read_number(streamer, &value))
  34. break;
  35. if (!read_whitespace(context, streamer))
  36. break;
  37. color_data.append({ (u8)value, (u8)value, (u8)value });
  38. }
  39. } else if (context.type == PGMLoadingContext::Type::RAWBITS) {
  40. u8 pixel;
  41. while (streamer.read(pixel)) {
  42. color_data.append({ pixel, pixel, pixel });
  43. }
  44. }
  45. size_t context_size = (u32)context.width * (u32)context.height;
  46. if (context_size != color_data.size()) {
  47. dbgln("Not enough color data in image.");
  48. return false;
  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. }