PPMLoader.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 "PPMLoader.h"
  8. #include "PortableImageLoaderCommon.h"
  9. #include <AK/Endian.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/StringBuilder.h>
  13. #include <LibGfx/Streamer.h>
  14. #include <string.h>
  15. namespace Gfx {
  16. bool read_image_data(PPMLoadingContext& context, Streamer& streamer)
  17. {
  18. Vector<Gfx::Color> color_data;
  19. color_data.ensure_capacity(context.width * context.height);
  20. if (context.type == PPMLoadingContext::Type::ASCII) {
  21. u16 red;
  22. u16 green;
  23. u16 blue;
  24. while (true) {
  25. if (!read_number(streamer, &red))
  26. break;
  27. if (!read_whitespace(context, streamer))
  28. break;
  29. if (!read_number(streamer, &green))
  30. break;
  31. if (!read_whitespace(context, streamer))
  32. break;
  33. if (!read_number(streamer, &blue))
  34. break;
  35. if (!read_whitespace(context, streamer))
  36. break;
  37. Color color { (u8)red, (u8)green, (u8)blue };
  38. if (context.format_details.max_val < 255)
  39. color = adjust_color(context.format_details.max_val, color);
  40. color_data.append(color);
  41. }
  42. } else if (context.type == PPMLoadingContext::Type::RAWBITS) {
  43. u8 pixel[3];
  44. while (streamer.read_bytes(pixel, 3)) {
  45. color_data.append({ pixel[0], pixel[1], pixel[2] });
  46. }
  47. }
  48. if (context.width * context.height != color_data.size())
  49. return false;
  50. if (!create_bitmap(context)) {
  51. return false;
  52. }
  53. set_pixels(context, color_data);
  54. context.state = PPMLoadingContext::State::Bitmap;
  55. return true;
  56. }
  57. }