PPMLoader.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. while (true) {
  22. auto const red_or_error = read_number(streamer);
  23. if (red_or_error.is_error())
  24. break;
  25. if (read_whitespace(context, streamer).is_error())
  26. break;
  27. auto const green_or_error = read_number(streamer);
  28. if (green_or_error.is_error())
  29. break;
  30. if (read_whitespace(context, streamer).is_error())
  31. break;
  32. auto const blue_or_error = read_number(streamer);
  33. if (blue_or_error.is_error())
  34. break;
  35. if (read_whitespace(context, streamer).is_error())
  36. break;
  37. Color color { (u8)red_or_error.value(), (u8)green_or_error.value(), (u8)blue_or_error.value() };
  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. }