PyGame将cStringIO加载为图像

时间:2013-03-26 17:53:40

标签: python image pygame stringio

所以,我在网上尝试了一些解决方案,但每个都会返回一个不同的错误。最近我决定尝试这样的事情:

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()

刚刚回归:

error: Can't seek in this data source

基本上,我的程序将加密/解密图像文件,并允许用户查看它们而不将解密的副本保存到硬盘驱动器。在另一个问题中,我被告知stringIO对象可以用于此目的,如果您将广泛使用它,则python文档会建议cStringIO。问题是pygame不希望将对象作为图像。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

将此添加到DummyFile

def tell(self):
    return self.pos

它认为您的文件类对象不可搜索,因为它缺少该方法。通过向DummyFile添加 __ getattr __ 方法并查看调用哪种方法来计算出来。