Skip to content

Instantly share code, notes, and snippets.

@nicholasRutherford
Created October 7, 2015 04:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholasRutherford/c95a55239e03ba99bab3 to your computer and use it in GitHub Desktop.
Save nicholasRutherford/c95a55239e03ba99bab3 to your computer and use it in GitHub Desktop.
Generating a ppm p6 file in python
# Define screen size
DISPLAY_WIDTH = 32 * 1 #32 pixels x 1 displays
DISPLAY_HEIGHT = 16
# Define a screen that has (width X height) numbers of 'pixels'. Each pixel is an RGB triplet
# with max value of 255. Even though our actual screen is 2-D it is stored as a 1-D array. Pixels
# 0 - 31 are the first row, 32 - 63 are the second row, etc.
screen = [[0,0,0] for x in xrange(self.DISPLAY_WIDTH*self.DISPLAY_HEIGHT)]
# Here is where you would set the value of each pixel
# Output
# Header values for the file
width=self.DISPLAY_WIDTH
height=self.DISPLAY_HEIGHT
comment='any comment string'
ftype='P6' #'P6' for binary
# First write the header values
ppmfile=open("picture.ppm",'wb+') # note the binary flag
ppmfile.write("%s\n" % (ftype))
ppmfile.write("#%s\n" % comment )
ppmfile.write("%d %d\n" % (width, height))
ppmfile.write("255\n")
# Then loop through the screen and write the values
for red,green,blue in self.screen:
ppmfile.write("%c%c%c" % (red,green,blue))
ppmfile.close()
@hankzhu123
Copy link

It helped me a lot.

@zeyutt
Copy link

zeyutt commented Aug 16, 2021

It is a really simple yet useful code snippet. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment