PPMLoader.cpp 2.1 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. auto const context_size = context.width * context.height;
  20. color_data.resize(context_size);
  21. if (context.type == PPMLoadingContext::Type::ASCII) {
  22. for (u64 i = 0; i < context_size; ++i) {
  23. auto const red_or_error = read_number(streamer);
  24. if (red_or_error.is_error())
  25. return false;
  26. if (read_whitespace(context, streamer).is_error())
  27. return false;
  28. auto const green_or_error = read_number(streamer);
  29. if (green_or_error.is_error())
  30. return false;
  31. if (read_whitespace(context, streamer).is_error())
  32. return false;
  33. auto const blue_or_error = read_number(streamer);
  34. if (blue_or_error.is_error())
  35. return false;
  36. if (read_whitespace(context, streamer).is_error())
  37. return false;
  38. Color color { (u8)red_or_error.value(), (u8)green_or_error.value(), (u8)blue_or_error.value() };
  39. if (context.format_details.max_val < 255)
  40. color = adjust_color(context.format_details.max_val, color);
  41. color_data[i] = color;
  42. }
  43. } else if (context.type == PPMLoadingContext::Type::RAWBITS) {
  44. for (u64 i = 0; i < context_size; ++i) {
  45. u8 pixel[3];
  46. if (!streamer.read_bytes(pixel, 3))
  47. return false;
  48. color_data[i] = { pixel[0], pixel[1], pixel[2] };
  49. }
  50. }
  51. if (!create_bitmap(context)) {
  52. return false;
  53. }
  54. set_pixels(context, color_data);
  55. context.state = PPMLoadingContext::State::Bitmap;
  56. return true;
  57. }
  58. }