PBMLoader.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 "PortableImageLoaderCommon.h"
  9. namespace Gfx {
  10. ErrorOr<void> read_image_data(PBMLoadingContext& context)
  11. {
  12. TRY(create_bitmap(context));
  13. auto& stream = *context.stream;
  14. auto const context_size = context.width * context.height;
  15. if (context.type == PBMLoadingContext::Type::ASCII) {
  16. for (u64 i = 0; i < context_size; ++i) {
  17. auto const byte = TRY(stream.read_value<u8>());
  18. if (byte == '0')
  19. context.bitmap->set_pixel(i % context.width, i / context.width, Color::White);
  20. else if (byte == '1')
  21. context.bitmap->set_pixel(i % context.width, i / context.width, Color::Black);
  22. else
  23. i--;
  24. }
  25. } else if (context.type == PBMLoadingContext::Type::RAWBITS) {
  26. for (u64 color_index = 0; color_index < context_size;) {
  27. auto byte = TRY(stream.read_value<u8>());
  28. for (int i = 0; i < 8; i++) {
  29. auto const val = byte & 0x80;
  30. if (val == 0)
  31. context.bitmap->set_pixel(color_index % context.width, color_index / context.width, Color::White);
  32. else
  33. context.bitmap->set_pixel(color_index % context.width, color_index / context.width, Color::Black);
  34. byte = byte << 1;
  35. color_index++;
  36. if (color_index % context.width == 0) {
  37. break;
  38. }
  39. }
  40. }
  41. }
  42. return {};
  43. }
  44. }