Reputation: 385
I am trying to add one pixel to base64 picture. I want my express server to receive base64 image string (e.g. data:image/png;base64,iVBORw0KG...
) for sake of example let's say that the image is 100x100px and I want to add red pixel on x=10 and y=10, and after that send it as response. I don't have any workable code to show because I don't know how to do it and can't find anything on internet. Express part is not an issue I know how to make that. Looking for any pointer in right direction, any recommendation or parts of code. Thank you!
Upvotes: 1
Views: 1651
Reputation: 531
You can use the Jimp package to do that.
Here is a simple example setting a red pixel on a 100x100 black png image:
const Jimp = require('jimp');
const { promisify } = require('util');
const MIME_TYPE = 'image/png';
const IMAGE_URL = `data:${MIME_TYPE};base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAA0SURBVHhe7cEBDQAAAMKg909tDjcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAbNXWUAAEE/b5iAAAAAElFTkSuQmCC`;
const coords = {
x: 10,
y: 10
};
const color = {
r: 255,
g: 0,
b: 0,
a: 255
};
async function main(color, coords) {
const imageData = IMAGE_URL.split(',').pop();
const image = await Jimp.read(Buffer.from(imageData, 'base64'));
const hexColor = Jimp.rgbaToInt(color.r, color.g, color.b, color.a);
image.setPixelColor(hexColor, coords.x, coords.y);
const toBase64 = promisify(image.getBase64).bind(image);
return await toBase64(MIME_TYPE);
}
main(color, coords)
.then(console.log)
.catch(console.error);
Upvotes: 2