Created
September 18, 2023 10:46
-
-
Save quentint/9f2b6ccf5be838778c9853204627061f to your computer and use it in GitHub Desktop.
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
import Jimp from "jimp"; | |
const imageUrl = 'https://i.scdn.co/image/ab67616d00001e02e8b066f70c206551210d902b'; | |
const outputImagePath = './output.jpg'; | |
type RGB = [number, number, number]; | |
type ColorMapping = { [color: string]: RGB }; | |
// Colors mapping to their RGB values | |
const predefinedColors: ColorMapping = { | |
BLACK: [0, 0, 0], | |
RED: [255, 0, 0], | |
GREEN: [0, 255, 0], | |
YELLOW: [255, 255, 0], | |
MAGENTA: [255, 0, 255], | |
BLUE: [0, 0, 255], | |
CYAN: [0, 255, 255], | |
WHITE: [255, 255, 255] | |
}; | |
// Function to calculate Euclidean distance | |
function colorDistance(rgb1: RGB, rgb2: RGB): number { | |
const [r1, g1, b1] = rgb1; | |
const [r2, g2, b2] = rgb2; | |
return Math.sqrt(Math.pow((r2 - r1), 2) + Math.pow((g2 - g1), 2) + Math.pow((b2 - b1), 2)); | |
} | |
// Function to get closest color | |
function getClosestColor(inputColor: RGB): string { | |
let minDistance = Infinity; | |
let closestColor = ""; | |
for (const color in predefinedColors) { | |
const distance = colorDistance(inputColor, predefinedColors[color]); | |
if (distance < minDistance) { | |
minDistance = distance; | |
closestColor = color; | |
} | |
} | |
return closestColor; | |
} | |
Jimp.read(imageUrl) | |
.then(image => { | |
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { | |
const red = this.bitmap.data[idx]; | |
const green = this.bitmap.data[idx + 1]; | |
const blue = this.bitmap.data[idx + 2]; | |
const closestColor = getClosestColor([red, green, blue]); | |
this.bitmap.data[idx] = predefinedColors[closestColor][0]; | |
this.bitmap.data[idx + 1] = predefinedColors[closestColor][1]; | |
this.bitmap.data[idx + 2] = predefinedColors[closestColor][2]; | |
}); | |
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