PBMLoader.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. auto& stream = *context.stream;
  13. Vector<Gfx::Color> color_data;
  14. auto const context_size = context.width * context.height;
  15. color_data.resize(context_size);
  16. if (context.type == PBMLoadingContext::Type::ASCII) {
  17. for (u64 i = 0; i < context_size; ++i) {
  18. auto const byte = TRY(stream.read_value<u8>());
  19. if (byte == '0')
  20. color_data[i] = Color::White;
  21. else if (byte == '1')
  22. color_data[i] = Color::Black;
  23. else
  24. i--;
  25. }
  26. } else if (context.type == PBMLoadingContext::Type::RAWBITS) {
  27. for (u64 color_index = 0; color_index < context_size;) {
  28. auto byte = TRY(stream.read_value<u8>());
  29. for (int i = 0; i < 8; i++) {
  30. auto const val = byte & 0x80;
  31. if (val == 0)
  32. color_data[color_index] = Color::White;
  33. else
  34. color_data[color_index] = Color::Black;
  35. byte = byte << 1;
  36. color_index++;
  37. if (color_index % context.width == 0) {
  38. break;
  39. }
  40. }
  41. }
  42. }
  43. TRY(create_bitmap(context));
  44. set_pixels(context, color_data);
  45. context.state = PBMLoadingContext::State::Bitmap;
  46. return {};
  47. }
  48. }