Search code examples
pythonimagepygamestringio

PyGame load cStringIO as image


So, I've tried a few solutions on the net for this but each one returns a different error. Most recently I've decided to try something like:

import cStringIO, pygame, os
from pygame.locals import *

pygame.init()
mainClock = pygame.time.Clock()
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('StringIO Test')

with open("image.png", "rb") as infile:
    outfile = cStringIO.StringIO()
    outfile.write(infile.read())


class DummyFile:
    def __init__(self, data):
       self.data = data
        self.pos = 0

    def read(self, size=None):
        start = self.pos
        end = len(self.data) - 1

        if size is not None:
            end = min(len(self.data), self.pos + size)

        self.pos = end
        return self.data[start:end]

    def seek(self, offset, whence=0):
        if whence == 0:
            self.pos = offset
        elif whence == 1:
            self.pos = self.pos + offset
        elif whence == 2:
            self.pos = len(data) + offset    

    def write(self):
        pass

while True:
    windowSurface.fill((0,0,0))
    testIm = pygame.image.load(DummyFile(outfile.getvalue()))
    testImRect = testIm.get_rect()
    testImRect.topleft = (0,0)
    windowSurface.blit(testIm, testImRect)
    pygame.display.flip()

Which just returns:

error: Can't seek in this data source

Essentially, my program is going to encrypt/decrypt image files, and allow the user to view them without saving the decrypted copy to the hard drive. In another question I was told stringIO objects work for this purpose, and the python docs suggest cStringIO if you're going to be using it extensively. The problem being pygame doesn't want to take the object as an image. Any ideas?


Solution

  • Add this to DummyFile

    def tell(self):
        return self.pos
    

    It thinks your file-like object is not seekable because it is missing that method. Figured it out by adding a __getattr__ method to DummyFile and seeing what kind of methods get called.