Back

Version 73

5/2/2024
/** @jsxImportSource npm:hono@3/jsx */
import { Hono } from "https://esm.sh/hono@3";

const EXAMPLE_URL = "https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg";
const PERCENT_COVERAGE = 10; // lower is faster, but higher is more accurate

function getPixelIndex(numToRound) {
// Each pixel is 4 units long: r,g,b,a
const remainder = numToRound % 4;
if (remainder == 0) return numToRound;
return numToRound + 4 - remainder;
}

export async function getColor(src: string = EXAMPLE_URL): Promise<string> {
const { default: Jimp } = await import("npm:jimp");
const image = await Jimp.read(src);
const store = {};
const total_pixels = image.bitmap.width * image.bitmap.height;
const coverage = total_pixels * PERCENT_COVERAGE / 100;
const data = image.bitmap.data;
const max_pixel_index = total_pixels - 1;

for (let i = 0; i < coverage; ++i) {
const x = getPixelIndex(Math.floor(Math.random() * max_pixel_index));
const key = `${data[x]},${data[x + 1]},${data[x + 2]}`;
const val = store[key];
store[key] = val ? val + 1 : 1;
}

const rgb_code = Object.keys(store).reduce((a, b) => store[a] > store[b] ? a : b);
return `rgb(${rgb_code})`;
}

const template = (children) => (
<html>
<head>
stevekrouse-getcolor.web.val.run
Updated: May 3, 2024