Skip to content

Instantly share code, notes, and snippets.

@quentint
Created September 18, 2023 10:46
Show Gist options
  • Save quentint/723638af57ecd98e5e60a0c60c1e5a37 to your computer and use it in GitHub Desktop.
Save quentint/723638af57ecd98e5e60a0c60c1e5a37 to your computer and use it in GitHub Desktop.
import Jimp from 'jimp';
// const imageUrl = 'https://i.scdn.co/image/ab67616d00001e02e8b066f70c206551210d902b';
// const imageUrl = 'https://i.scdn.co/image/ab67616d00001e02921f7aa6349a070b6f26b3ff';
// const imageUrl = 'https://i.scdn.co/image/ab67616d0000b2734f70220d934183ce2db16d6a';
const imageUrl = 'https://i.scdn.co/image/ab67616d00001e022eae3ae708586c21b6eee710';
const outputImagePath = './output.jpg';
type RGB = [number, number, number];
type Grayscale = number;
// Grayscale values
const grayScales: Grayscale[] = [0, 40, 50, 60, 70, 80, 90, 100];
// Function to calculate absolute difference
function colorDistance(gs1: Grayscale, gs2: Grayscale): number {
return Math.abs(gs1 - gs2);
}
// Function to convert RGB to grayscale
function rgbToGrayscale(rgb: RGB): Grayscale {
return (rgb[0] + rgb[1] + rgb[2]) / 3 / 255 * 100;
}
// Function to get the closest color in grayscale and convert it to RGB
function getClosestRGB(inputColor: RGB): number {
const grayscale = rgbToGrayscale(inputColor);
let minDistance = Infinity;
let closestColor = null
for (const color of grayScales) {
const distance = colorDistance(grayscale, color);
if (distance < minDistance) {
minDistance = distance;
closestColor = color;
}
}
return closestColor !== null ? closestColor/100*255 : 0;
}
Jimp.read(imageUrl)
.then(image => {
image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => {
const red = image.bitmap.data[idx];
const green = image.bitmap.data[idx + 1];
const blue = image.bitmap.data[idx + 2];
const rgb = getClosestRGB([red, green, blue]);
image.bitmap.data[idx] = rgb;
image.bitmap.data[idx + 1] = rgb;
image.bitmap.data[idx + 2] = rgb;
});
return image
.resize(40, Jimp.AUTO)
.writeAsync(outputImagePath);
})
.catch(err => {
console.error(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment