Created
June 20, 2023 10:43
-
-
Save a13e/607ded61c15e1d347d628b09d9d2a23a 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
| const sharp = require('sharp'); | |
| const countColors = (sharpBuffer) => { | |
| let colorCounts = {}; | |
| for (let i = 0; i < sharpBuffer.length; i += 3) { | |
| const r = sharpBuffer[i]; | |
| const g = sharpBuffer[i + 1]; | |
| const b = sharpBuffer[i + 2]; | |
| const rgb = `rgb(${r},${g},${b})`; | |
| if (!colorCounts[rgb]) { | |
| colorCounts[rgb] = 0; | |
| } | |
| colorCounts[rgb]++; | |
| } | |
| return colorCounts; | |
| } | |
| const extractDominantColor = (sharpBuffer) => { | |
| const colorCounts = countColors(sharpBuffer); | |
| // Find dominant color | |
| let dominantColor = null; | |
| let maxCount = 0; | |
| for (const color in colorCounts) { | |
| if (colorCounts[color] > maxCount) { | |
| maxCount = colorCounts[color]; | |
| dominantColor = color; | |
| } | |
| } | |
| return dominantColor | |
| } | |
| // Load and process image | |
| (async () => { | |
| try { | |
| const data = await sharp('./1910_Thankyou_Thankyou.jpg') // Put your image path here | |
| .resize(16, 16) | |
| .raw() | |
| .toBuffer() | |
| const dominantColor = extractDominantColor(data) | |
| console.log('Dominant color:', dominantColor); | |
| } catch (err) { | |
| console.error('Error processing image', err); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment