# SDL - Replacing colors on a surface.

This topic is 4798 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Could someone explain how I would go about replacing one color on a surface? Thanks in advance.

##### Share on other sites
MapRGB for the color to replace, MapRGB for the color to replace with (using the surface that the color rep...

You know what? Cut an paste is easier. I'll public domain this for ya.

void sprite::colorReplace(unsigned char r1,unsigned char g1,unsigned char b1,						unsigned char r2,unsigned char g2,unsigned char b2){	int coltemp1 = SDL_MapRGB(s->format,r1,g1,b1);	int coltemp2 = SDL_MapRGB(s->format,r2,g2,b2);	SDL_LockSurface(s);	for(int y=0;y<s->h;y++) {		for(int x=0;x<s->w;x++) {			if(getpixel(x,y) == coltemp1)				putpixel(x,y,coltemp2);		}	}	SDL_UnlockSurface(s);}

get/putpixel are from the sdl docs, and 's' is the surface

##### Share on other sites
Do you have the link to the exact location of the whole getpixel putpixel thing? If not thanks again anyway!

##### Share on other sites
Nevermind I found it! :D

##### Share on other sites
I realize C-Junkie's way is much nicer but I have done it using colorkeys in SDL. I create a temp surface the same size as the original image or section of the image, fill it with the color I want to replace the old color with then set the colorkey on the original surface to the color I want to switch from, blit to the temp surface then blit back to the original surface, delete the temp surface and reset the colorkey to whatever it was before on the original. This works well for me if I have a set of images on a single surface and I only want to change a color for one of them. Obviously this isn't one of those highly optimized or thought out routines, it just works for me.

##### Share on other sites
This works great, but I've got one problem. I'm using the same image for several different surfaces. When I change the color for 1 surface it does it for all of them as if it were changing the file instead. In all this works well. Thank you. I'll try and sort out this problemo.

##### Share on other sites
Quote:
 Original post by AntiGuyThis works great, but I've got one problem. I'm using the same image for several different surfaces. When I change the color for 1 surface it does it for all of them as if it were changing the file instead. In all this works well. Thank you. I'll try and sort out this problemo.

There's probably better ways to do this, but you just need another SDL_Surface*, so you could use a function like SDL_DisplayFormat(SDL_Surface *surface), that returns a pointer to a SDL surface and then change colors on the new one. You'll still have your old surface for whatever you want.

##### Share on other sites
I don't quite get it. Mind putting it in code?

Note: It works when I use SDL_LoadIMG after the transfer but that takes a while.