Live Chat Icon For mobile
Live Chat Icon

How can I swap colors in a bitmap or icon

Platform: WinForms| Category: Bitmaps and Images

You use ImageAttributes, adding a ColorMap that swaps the colors. Here is a code snippet.

	Bitmap originalBMP = (Bitmap) Image.FromFile(@'c:\circle.bmp');

	//make a copy so original will still be available
	Bitmap swappedBMP = new Bitmap(originalBMP); 

	Graphics g = Graphics.FromImage(swappedBMP);
	// Create a color map.
	ColorMap[] colorSwapper= new ColorMap[2];
	colorSwapper[0] = new ColorMap();
	colorSwapper[1] = new ColorMap();
	colorSwapper[0].OldColor = Color.Red; //red changes to yellow
	colorSwapper[0].NewColor = Color.Yellow;
	colorSwapper[1].OldColor = Color.Blue;//blue changes to green
	colorSwapper[1].NewColor = Color.Green;
	// Create an ImageAttributes object, and call SetRemapTable
	ImageAttributes imageAttr = new ImageAttributes();
	//overdraw the bitmap with swapped colors
	g.DrawImage(swappedBMP, new Rectangle(0, 0, 
		swappedBMP.Width, swappedBMP.Height),0, 0, swappedBMP.Width, 
		swappedBMP.Height, GraphicsUnit.Pixel, imageAttr);
	pictureBox1.Image = swappedBMP;

Here is similar code that wraps this technique in a method that swaps a single color.

	protected void DrawMyBitmap(Graphics gph, Color oldColor, Color newColor, Bitmap baseImage, Rectangle rect)
		ImageAttributes imgattr = new ImageAttributes();
		ColorMap[] clrmap = new ColorMap[1]{ new ColorMap() };

		clrmap[0].OldColor = oldColor;
		clrmap[0].NewColor = newColor;				


		gph.DrawImage(baseImage,rect,0,0,rect.Width, rect.Height,GraphicsUnit.Pixel,imgattr);

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.