PBMLoader.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 "PBMLoader.h"
  8. #include "AK/Endian.h"
  9. #include "PortableImageLoaderCommon.h"
  10. #include "Userland/Libraries/LibGfx/Streamer.h"
  11. #include <string.h>
  12. namespace Gfx {
  13. bool read_image_data(PBMLoadingContext& context, Streamer& streamer)
  14. {
  15. Vector<Gfx::Color> color_data;
  16. auto const context_size = context.width * context.height;
  17. color_data.resize(context_size);
  18. if (context.type == PBMLoadingContext::Type::ASCII) {
  19. for (u64 i = 0; i < context_size; ++i) {
  20. u8 byte;
  21. if (!streamer.read(byte))
  22. return false;
  23. if (byte == '0')
  24. color_data[i] = Color::White;
  25. else if (byte == '1')
  26. color_data[i] = Color::Black;
  27. else
  28. i--;
  29. }
  30. } else if (context.type == PBMLoadingContext::Type::RAWBITS) {
  31. for (u64 color_index = 0; color_index < context_size;) {
  32. u8 byte;
  33. if (!streamer.read(byte))
  34. return false;
  35. for (int i = 0; i < 8; i++) {
  36. int val = byte & 0x80;
  37. if (val == 0)
  38. color_data[color_index] = Color::White;
  39. else
  40. color_data[color_index] = Color::Black;
  41. byte = byte << 1;
  42. color_index++;
  43. if (color_index % context.width == 0) {
  44. break;
  45. }
  46. }
  47. }
  48. }
  49. if (!create_bitmap(context)) {
  50. return false;
  51. }
  52. set_pixels(context, color_data);
  53. context.state = PBMLoadingContext::State::Bitmap;
  54. return true;
  55. }
  56. }