Advertisement

Desaturation in SDL

Started by January 12, 2005 11:19 PM
21 comments, last by Mastadex 20 years, 1 month ago
A few suggestions:

The creators of SDL went through a lot of trouble to keep SDL as cross platform as possible. If at all possible you should try to use the variable types as they have defined them in order to keep this cross platform portability (i.e. Sint32 instead of int).

Check out the getpixel and putpixel functions as they appear in the SDL documentation. They handle the pixels no matter the bit depth of the surface. You can use the SDL_MapRGB and SDL_GetRGB functions to make sure you convert the pixels to the correct format.

Another helpful hint is that doing pixel manipulation on a hardware surface is extremely slow. What I would recomend doing is creating the new surface in software, copying the screen to the new surface with a SDL_BlitSurface call and doing your pixel manipulation there, then copying the whole thing at once back to the original.

Also, adding weight to the RGB compnents of a pixel is a good idea no matter what format it is in. I highly recomend using the information I provided in my last post to get a more accurate greyscale image.
Evillive2
Thanks Guys, Here is the Source for it, if anyone wants to use it.

SDL_Surface *Desaturate(SDL_Surface *orig){	// The Desaturated Image memory location	SDL_Surface *newScr;	// Create a new Surface	newScr = SDL_CreateRGBSurface(SDL_HWSURFACE, orig->w, orig->h, 32, rmask, gmask, bmask, amask);	SDL_BlitSurface(orig, NULL, newScr, NULL);	// Desaturate the new Image	for (int x = 0; x < newScr->w; ++x)	{		for (int y = 0; y < newScr->h; ++y)		{			// Locks the Surface for pixel Manipulation			if (SDL_LockSurface(newScr) < 0)			{				// ERROR				return NULL;			}			// Read the pixel information for the current image			Uint32 color = GetPixel(newScr, x, y);			// Takes the Blue Channel			float b = color & 0xFF;			color = color >> 8;			// Takes the green Channel			float g = color & 0xFF;			color = color >> 8;			// Takes the Red Channel			float r = color & 0xFF;						// Take the average of the three channels			int brightness = (r + g + b) / 3;			// Desaturation of the current pixel and write it to image			color = brightness | (brightness << 8) | (brightness << 16);			// This adds the Alhpa Channel Because Its the way PNG files are stored			color += 4278190080;			// Write the Color Information to the Surface			PutPixel(newScr, x, y, color);			SDL_UnlockSurface(newScr);		}	}   	// Update the newly created Surface	SDL_UpdateRect(newScr, 0, 0, newScr->w, newScr->h);	// Delete the original Surface	SDL_FreeSurface(orig);	return newScr;}

This topic is closed to new replies.

Advertisement