Design system.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

34 lines
1.3 KiB

  1. import ColorThief from 'colorthief';
  2. import {DEFAULT_PALETTE_COLOR_COUNT, GetImageMetadataOptions, ImageMetadata} from './common';
  3. const doGetImageMetadata = async (thisImage: HTMLImageElement, options = {} as GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => {
  4. const { paletteColorCount = DEFAULT_PALETTE_COLOR_COUNT } = options;
  5. const colorThief = new ColorThief();
  6. const palette = await colorThief.getPalette(thisImage, paletteColorCount);
  7. return {
  8. width: thisImage.naturalWidth,
  9. height: thisImage.naturalHeight,
  10. palette,
  11. };
  12. };
  13. export const getMetadataFromElement = (thisImage: HTMLImageElement, options?: GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => doGetImageMetadata(thisImage, options);
  14. export const getMetadataFromUrl = (imageUrl: string, options = {} as GetImageMetadataOptions): Promise<Partial<ImageMetadata>> => new Promise((resolve, reject) => {
  15. const image = new Image();
  16. image.addEventListener('load', async (imageLoadEvent) => {
  17. const thisImage = imageLoadEvent.currentTarget as HTMLImageElement;
  18. const metadata = await doGetImageMetadata(thisImage, options);
  19. image.remove();
  20. resolve(metadata);
  21. });
  22. image.addEventListener('error', () => {
  23. reject(new Error('Could not load URL as image'));
  24. image.remove();
  25. });
  26. image.src = imageUrl;
  27. });