Skip to content

Instantly share code, notes, and snippets.

@1mehdifaraji
Created August 13, 2025 11:58
Show Gist options
  • Select an option

  • Save 1mehdifaraji/8c89a1742256030a04b29cc14911a6c3 to your computer and use it in GitHub Desktop.

Select an option

Save 1mehdifaraji/8c89a1742256030a04b29cc14911a6c3 to your computer and use it in GitHub Desktop.
Dominant image color extractor
/* 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