From cee753d25c228e6ad670343b851cdcf3525107da Mon Sep 17 00:00:00 2001 From: Andrew McNutt Date: Sat, 19 Oct 2024 19:19:17 -0600 Subject: [PATCH] Extract color palette from image (#152) * Add mechanism for extract color palette from image * types * better types --- apps/color-buddy/package.json | 1 + apps/color-buddy/src/controls/NewPal.svelte | 59 +- apps/color-buddy/src/custom-types.d.ts | 17 + yarn.lock | 2686 +++++++++++++------ 4 files changed, 1905 insertions(+), 858 deletions(-) diff --git a/apps/color-buddy/package.json b/apps/color-buddy/package.json index f95a6de2..82e6cb9c 100644 --- a/apps/color-buddy/package.json +++ b/apps/color-buddy/package.json @@ -46,6 +46,7 @@ "color-buddy-palette": "*", "color-buddy-palette-lint": "*", "colorjs.io": "^0.5.2", + "colorthief": "^2.6.0", "d3-scale": "^4.0.2", "d3-shape": "^3.2.0", "driver.js": "^1.3.1", diff --git a/apps/color-buddy/src/controls/NewPal.svelte b/apps/color-buddy/src/controls/NewPal.svelte index bae24b88..10db4348 100644 --- a/apps/color-buddy/src/controls/NewPal.svelte +++ b/apps/color-buddy/src/controls/NewPal.svelte @@ -6,9 +6,10 @@ import configStore from "../stores/config-store"; import { processBodyTextToColors, newGenericPal } from "../lib/utils"; - import { buttonStyle, denseButtonStyle } from "../lib/styles"; + import { buttonStyle } from "../lib/styles"; import Tooltip from "../components/Tooltip.svelte"; import SuggestColorPal from "./SuggestColorPal.svelte"; + import ColorThief from "colorthief"; $: currentPal = $colorStore.palettes[$colorStore.currentPal]; $: colorSpace = currentPal ? currentPal.colorSpace : "lab"; @@ -39,6 +40,48 @@ return; } } + let palFromImgError = ""; + let palFromImgState: "idle" | "loading" = "idle"; + function processImg(e: any, onClick: () => void) { + const colorThief = new ColorThief(); + palFromImgState = "loading"; + try { + const target = e.target as HTMLInputElement; + const files = target?.files; + console.log(files); + if (!files) { + return; + } + const file = [...files].at(0); + if (!file) { + return; + } + const reader = new FileReader(); + reader.onload = (e) => { + const img = new Image(); + img.src = (e.target as FileReader).result as string; + img.onload = () => { + try { + const colors = colorThief.getPalette(img, 5) as number[][]; + const palRGB = colors.map((x) => `rgb(${x.join(", ")})`); + const pal = makePalFromString(palRGB); + console.log(colors); + + newPal(pal, onClick); + } catch (e) { + console.error(e); + palFromImgState = "idle"; + palFromImgError = "Error processing image"; + } + }; + }; + reader.readAsDataURL(file); + } catch (e) { + console.error(e); + palFromImgError = "Error processing image"; + palFromImgState = "idle"; + } + } @@ -114,6 +157,20 @@
Generate a new palette using AI
{/if} +
+
Generate From Image (png or jpg)
+ processImg(e, onClick)} + /> + {#if palFromImgState === "loading"} +
Loading...
+ {/if} + {#if palFromImgError} +
{palFromImgError}
+ {/if}