tags:

views:

6465

answers:

3

I would like to know is there any way by which we can change the Image color at runtime. for e.g lets say I am having a JPG bind to an Image control of ASP.Net. Next I am having a dropdown List which gives me the various color option like red,gree,etc. I would now like to change the color of the Image to the one selected in the droprdown List.

+2  A: 

Here is a code sample that loads a JPEG, changes any red pixels in the image to blue, and then displays the bitmap in a picture box:

Bitmap bmp = (Bitmap)Bitmap.FromFile("image.jpg");
for (int x = 0; x < bmp.Width; x++)
{
    for (int y = 0; y < bmp.Height; y++)
    {
        if (bmp.GetPixel(x, y) == Color.Red)
        {
            bmp.SetPixel(x, y, Color.Blue);
        }
    }
}
pictureBox1.Image = bmp;

Warning: GetPixel and SetPixel are incredibly slow. If your images are large and/or performance is an issue, there is a much faster way to read and write pixels in .NET, but it's a little bit more work.

MusiGenesis
+2  A: 

+1 @MusiGenesis post. Get/Set pixel methods are almost useless if you seek performance.

The solution (really, not too difficult to implement):

  1. Unsafe mode
  2. Locking the in-memory bitmap/image
  3. Do your stuff

Massive performance improvements :).

See this: C# unsafe image processing.

+1  A: 

Your question is in did very vague. if you would like to change pixels on image there's an answer how to do it by MusiGenesis. For that matter you will have to make a postback on every colour change.

If you're just changing colour of a square to match selection, you can do it all on the client by having a div of certain size that would change its colour to the selected one

getElementById('changeDiv').style.backgroundColor = '#999';

Changing image background
If you'd just like to change background of an image, than I suggest you create an image with Alpha channel and save it in PNG format. Place that image inside of the same div I used it previously and you're use the same code as above.

Robert Koritnik
not related... see c# tag
Elijah Glover
thanks... my bad. Haven't checked that one... But since he's trying to do something that is intrinsically slow and bad experience maybe he's not really aware of the possibilities.
Robert Koritnik