1

I'm making a game which includes image, text, and audio files located in a password-protected .zip. I'm trying to use pygame.image.load and show the image like this:

from zipfile import ZipFile
import pygame
import pyganim
import sys

pygame.init()
root = pygame.display.set_mode((320, 240), 0, 32)
pygame.display.set_caption('image load test')



archive = ZipFile("spam.zip", 'r')
mcimg = archive.read("a.png", pwd=b'onlyforthedev')

mc = pygame.image.load(mcimg)

anime = pyganim.PygAnimation([(mcimg, 100),
                              (mcimg, 100)])
anime.play()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()


    windowSurface.fill((100, 50, 50))
    anime.blit(root, (100, 50))
    pygame.display.update()

This is the error I get from this:

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\VERY IMPORTANT FOR GAME DISTRIBUTION\few.py", 
  line 41, in <module>
  mc = pygame.image.load(mcimg)
  pygame.error: File path '�PNG


  ' contains null characters
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
fisch
  • 31
  • 1
  • 3
  • Possible duplicate of [Python code to create a password encrypted zip file?](https://stackoverflow.com/questions/2195747/python-code-to-create-a-password-encrypted-zip-file) – tangoal Sep 11 '18 at 21:13
  • Your code is already doing exactly what you asked how to do: `mcimg = archive.read("a.png", pwd=b'onlyforthedev')`. So… what's the problem you're asking about? – abarnert Sep 11 '18 at 21:18
  • I just added the error message – fisch Sep 11 '18 at 21:21

1 Answers1

1

The function pygame.image.load can load an image from a file source. You can pass either a filename or a Python file-like object.

But, actually you give the image bytes.

To fix that you can wrap your bytes in an io.Bytes instance and use it as a file-like object:

import zipfile
import io

with zipfile.ZipFile("spam.zip", 'r') as archive:
    mcimg = archive.read("a.png", pwd=b'onlyforthedev')

mc = pygame.image.load(io.BytesIO(mcimg))
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • Thank you so much, this helped for the image part. But what about the audio and text files? can they be accessed the same way? – fisch Sep 12 '18 at 11:19
  • @ClaraDocej, sure. For instance, you can use [pygame.mixer.music.load](https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load) to load the music for playback… – Laurent LAPORTE Sep 12 '18 at 12:39
  • tried doing that exactly, but it crashed all of python. – fisch Sep 12 '18 at 16:10
  • @ClaraDocej, it’s better to post another question with a sample of your code and the trace back. It’s easier to diagnose and answer. – Laurent LAPORTE Sep 13 '18 at 04:53