Monday, December 1, 2008

CHANGE IMAGE COLOR USING C# ( GRAPHICS GDI+ )

·

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color NewCol = Color.Green; // REPLACED COLOR
Bitmap b = new Bitmap(Server.MapPath("clipart.png"));
b = ChangeImageColor((System.Drawing.Image)b, NewCol);
b.Save(Server.MapPath("NewImage.png"), ImageFormat.Png);
b.Dispose();
}
}


private Bitmap ChangeImageColor(System.Drawing.Image source, Color nCol)
{

// Create a bitmap from the image

Bitmap bmp = new Bitmap(source);



// Loop through each pixel in the bitmap. If we find

// a transparent pixel, we leave it alone.

for (int y = 0; y < bmp.Height; y++)
{

for (int x = 0; x < bmp.Width; x++)
{

// Get the color of the current pixel

Color col = bmp.GetPixel(x, y);


if (col.A != 0) //non alpha or any matched color
{

int r = (int)(nCol.R);

int g = (int)(nCol.G);

int b = (int)(nCol.B);



// To make the image brighter, increase this number

int light = 0;



// Create the new gray color

Color newColor = Color.FromArgb(
(r + light > 255 ? r : r + light),

(g + light > 255 ? g : g + light),

(b + light > 255 ? b : b + light));



bmp.SetPixel(x, y, newColor);

}



}

}

return bmp;
}

NOTE: Image color must be in single and image file must be transparent image.
This code helps you for clipart image to replace one color to other color.


Look at these images.

Old Image :



New Image :

0 comments: