Skip to content

Instantly share code, notes, and snippets.

@villares
Last active July 29, 2023 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save villares/3e00c5c4e3366b18ebadb9073e46c6d1 to your computer and use it in GitHub Desktop.
Save villares/3e00c5c4e3366b18ebadb9073e46c6d1 to your computer and use it in GitHub Desktop.
monkey patching a Py5Image to allow pickling
import pickle
import py5
from py5 import Py5Image
old_new = Py5Image.__new__
def new_new(self, *args):
if args:
return old_new(self, *args)
else:
return object.__new__(Py5Image)
def getstate(self):
self.load_np_pixels()
return self.np_pixels
def setstate(self, d):
img = py5.create_image_from_numpy(d)
#self._instace = img._instance
self.__dict__ = img.__dict__
def setup():
global img, unpickled_img
py5.size(800, 800)
Py5Image.__getstate__ = getstate
Py5Image.__setstate__ = setstate
Py5Image.__new__ = new_new
img_path = 'sample.png' # Sample from sketh 2023_07_22
img = py5.load_image(img_path)
unpickled_img = None
def draw():
if unpickled_img is not None:
py5.image(unpickled_img, 0, 0)
def key_pressed():
if py5.key == 'd':
with open('a.pickle', 'wb') as f:
pickle.dump(img, f)
elif py5.key == 'l':
global unpickled_img
with open('a.pickle', 'rb') as f:
unpickled_img = pickle.load(f)
py5.run_sketch(block=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment