Created
August 13, 2025 11:58
-
-
Save 1mehdifaraji/8c89a1742256030a04b29cc14911a6c3 to your computer and use it in GitHub Desktop.
Dominant image color extractor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* eslint-disable @next/next/no-img-element */ | |
| "use client"; | |
| import ColorThief from "colorthief"; | |
| import type { HTMLProps } from "react"; | |
| import { useState } from "react"; | |
| export const ProductImage = ({ ...props }: HTMLProps<HTMLImageElement>) => { | |
| const [color, setColor] = useState(""); | |
| const handleImageLoad = (imgEl: HTMLImageElement) => { | |
| try { | |
| const colorThief = new ColorThief(); | |
| const rgb = colorThief.getColor(imgEl); | |
| const hex = `#${rgb.map((c) => c.toString(16).padStart(2, "0")).join("")}`; | |
| setColor(hex); | |
| } catch (err) { | |
| console.error("Color extraction failed:", err); | |
| } | |
| }; | |
| return ( | |
| <div> | |
| <div | |
| style={{ | |
| backgroundColor: color, | |
| }} | |
| > | |
| {JSON.stringify(color)} | |
| </div> | |
| <img | |
| alt="product-icon" | |
| crossOrigin="anonymous" | |
| ref={(el) => { | |
| if (el && el.complete) handleImageLoad(el); | |
| }} | |
| onLoad={(e) => handleImageLoad(e.currentTarget as HTMLImageElement)} | |
| {...props} | |
| /> | |
| </div> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment