[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] picklable Surface. Anyone made code to pickle a Surface?
René Dudfield wrote:
has anyone made code to pickle a Surface?
I'm thinking a tostring/fromstring type calls with the Surface
attributes pickled will suffice.
Yes, I did something like that once. I actually did it
via pixel arrays, but you might be able to do something
with the Surface.get_buffer() method.
These are the methods I used to pickle an object that
had a 'pixels' attribute holding a Surface.
from pygame import Surface, SRCALPHA
from Numeric import fromstring, reshape
from pygame.surfarray import pixels3d, pixels_alpha
...
def __getstate__(self):
pixels = self.pixels
rgb = pixels3d(pixels)
alpha = pixels_alpha(pixels)
d = self.__dict__.copy()
d['size'] = rgb.shape[:2]
d['rgb'] = rgb.tostring()
d['alpha'] = alpha.tostring()
del d['pixels']
return d
def __setstate__(self, d):
size = d.pop('size')
width, height = size
rgb_data = reshape(fromstring(d.pop('rgb'), 'b'), (width, height, 3))
alpha_data = reshape(fromstring(d.pop('alpha'), 'b'), (width, height))
pixels = Surface(size, SRCALPHA, 32)
rgb = pixels3d(pixels)
rgb[:,:,:] = rgb_data
alpha = pixels_alpha(pixels)
alpha[:,:] = alpha_data
d['size'] = size
d['pixels'] = pixels
self.__dict__.update(d)
--
Greg