ImageDecoder.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <LibGfx/ImageFormats/AVIFLoader.h>
  8. #include <LibGfx/ImageFormats/BMPLoader.h>
  9. #include <LibGfx/ImageFormats/GIFLoader.h>
  10. #include <LibGfx/ImageFormats/ICOLoader.h>
  11. #include <LibGfx/ImageFormats/ImageDecoder.h>
  12. #include <LibGfx/ImageFormats/JPEGLoader.h>
  13. #include <LibGfx/ImageFormats/JPEGXLLoader.h>
  14. #include <LibGfx/ImageFormats/PNGLoader.h>
  15. #include <LibGfx/ImageFormats/TIFFLoader.h>
  16. #include <LibGfx/ImageFormats/TinyVGLoader.h>
  17. #include <LibGfx/ImageFormats/WebPLoader.h>
  18. namespace Gfx {
  19. static ErrorOr<OwnPtr<ImageDecoderPlugin>> probe_and_sniff_for_appropriate_plugin(ReadonlyBytes bytes)
  20. {
  21. struct ImagePluginInitializer {
  22. bool (*sniff)(ReadonlyBytes) = nullptr;
  23. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> (*create)(ReadonlyBytes) = nullptr;
  24. };
  25. static constexpr ImagePluginInitializer s_initializers[] = {
  26. { BMPImageDecoderPlugin::sniff, BMPImageDecoderPlugin::create },
  27. { GIFImageDecoderPlugin::sniff, GIFImageDecoderPlugin::create },
  28. { ICOImageDecoderPlugin::sniff, ICOImageDecoderPlugin::create },
  29. { JPEGImageDecoderPlugin::sniff, JPEGImageDecoderPlugin::create },
  30. { JPEGXLImageDecoderPlugin::sniff, JPEGXLImageDecoderPlugin::create },
  31. { PNGImageDecoderPlugin::sniff, PNGImageDecoderPlugin::create },
  32. { TIFFImageDecoderPlugin::sniff, TIFFImageDecoderPlugin::create },
  33. { TinyVGImageDecoderPlugin::sniff, TinyVGImageDecoderPlugin::create },
  34. { WebPImageDecoderPlugin::sniff, WebPImageDecoderPlugin::create },
  35. { AVIFImageDecoderPlugin::sniff, AVIFImageDecoderPlugin::create }
  36. };
  37. for (auto& plugin : s_initializers) {
  38. auto sniff_result = plugin.sniff(bytes);
  39. if (!sniff_result)
  40. continue;
  41. return TRY(plugin.create(bytes));
  42. }
  43. return OwnPtr<ImageDecoderPlugin> {};
  44. }
  45. ErrorOr<RefPtr<ImageDecoder>> ImageDecoder::try_create_for_raw_bytes(ReadonlyBytes bytes, [[maybe_unused]] Optional<ByteString> mime_type)
  46. {
  47. if (auto plugin = TRY(probe_and_sniff_for_appropriate_plugin(bytes)); plugin)
  48. return adopt_ref_if_nonnull(new (nothrow) ImageDecoder(plugin.release_nonnull()));
  49. return RefPtr<ImageDecoder> {};
  50. }
  51. ImageDecoder::ImageDecoder(NonnullOwnPtr<ImageDecoderPlugin> plugin)
  52. : m_plugin(move(plugin))
  53. {
  54. }
  55. }