how to change the color of an image in a 400x500 pixel rectangle in javascript in matlab

You can use the HTML canvas element in conjunction with JavaScript to change the color of an image.

Here's an example code that changes the color of a square section of the image (400x500px) from red to green:

index.tsx
//Load the image onto the canvas
var img=document.getElementById('myImage');
var canvas=document.createElement('canvas');
var ctx=canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);

//Get the image data
var imageData=ctx.getImageData(0,0,400,500);

//Iterate over the pixels and change the color
for(var i=0;i<imageData.data.length;i+=4){
    if(imageData.data[i]==255 && imageData.data[i+1]==0 && imageData.data[i+2]==0){ //Red Color
        imageData.data[i]=0;
        imageData.data[i+1]=255;
        imageData.data[i+2]=0; //Green Color
    }
}

//Put the modified image data onto the canvas
ctx.putImageData(imageData,0,0);

//Replace the image with the modified canvas
img.src=canvas.toDataURL();
756 chars
26 lines

This code loads the image with ID "myImage" onto a canvas, gets the image data for a 400x500 pixel rectangle, iterates over the pixels, and replaces all red pixels with green pixels. Finally, the modified image data is placed back onto the canvas and replaces the original image.

gistlibby LogSnag