Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.

Ronin Magus

Creating a copy of SDL_Surface?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m trying to make an exact copy of an SDL_Surface, for the purpose of implementing an operator= function for my Image class. I''ve written a function which uses memcpy and CreateRGBSurface (with a set pixel depth, which I don''t like.. I''d want my pixel depth to vary.) The original surface, its transparent RGB colors (ints transr, transg, transb) are stored in an Image class. I''m wondering if there is a better way to copy the Surface than what I have implemented below, it seems terrible cumbersome and limited (by the depth in the call to SDL_CreateRGBSurfaceFrom. Could anyone at least tell me how to determine the depth of a surface?)
Image & Image::operator=(const Image & img)
	unsigned char * newPixels = NULL;
	unsigned int surfaceSize;
	// free the surface if there is already one loaded in this image


	surfaceSize = img.surf->w * img.surf->h * img.surf->format->BytesPerPixel;

	newPixels = new unsigned char[surfaceSize];

	// copy the data

	memcpy(newPixels, img.surf->pixels, surfaceSize);

	surf = SDL_CreateRGBSurfaceFrom(newPixels, img.surf->w, img.surf->h, 24, img.surf->pitch, img.surf->format->Rmask, img.surf->format->Gmask, img.surf->format->Bmask, img.surf->format->Amask);

	SetTransparent(img.transr, img.transg, img.transb);

	return *this;

Share this post

Link to post
Share on other sites


Isn't that giving you the depth?

In cas you want bit-depth (not pixel-depth), do this:


BTW, surface->pixels may be NULL, you should SDL_LockSurface() before accessing the pixels, and SDL_UnlockSurface() after.

More BTW:
You're leaking memory, unless you delete[] the surface->pixel later (and you only use this class with your own bitmaps, never ones returned from SDL_CreateRGBSurface() or SDL_LoadBMP() ).

A better solution would be something like this:

  • Create a new surface with SDL_CreateRGBSurface (not SDL_CreateRGBSurfaceFrom), using the same width/height/depth values as your original surface
  • Lock both surfaces
  • memcpy the original->pixels into the new->pixels
  • Unlock both surfaces

[edited by - TravisWells on March 16, 2003 11:34:39 PM]

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!