ppm-dump

From Noah.org
Jump to navigationJump to search
#!/usr/bin/env python

import sys

class ppm:

    '''This writes a 24-bit color PPM (PNM) formatted images (P3 or P6 format).
    This represents an RGB canvas to which you can use the draw() or spray()
    methods to modify pixels. When done you use the __str__() method to output
    the image as a PPM format. '''

    def __init__(self, width=100, height=100, is_ascii=False):

        self.width = width
        self.height = height
        self.is_ascii = is_ascii
        self.index_max = width*height
        self.plane_r = [0] * self.index_max
        self.plane_g = [0] * self.index_max
        self.plane_b = [0] * self.index_max
        self.imax = 255
        self.index = 0

    def draw (self, x, y, r, g, b):

        index = (y*self.width+x)%self.index_max
        self.plane_r[index] = r%256
        self.plane_g[index] = g%256
        self.plane_b[index] = b%256

    def spray (self, r, g, b):

        self.plane_r[self.index] = r%256
        self.plane_g[self.index] = g%256
        self.plane_b[self.index] = b%256
        self.index = (self.index+1)%self.index_max

    def __str__(self):

        ppm_str = ''
        if self.is_ascii:
            # ASCII
            ppm_str = ppm_str + "P3"
        else:
            # binary
            ppm_str = ppm_str + "P6"
        ppm_str = ppm_str + "\n"
        ppm_str = ppm_str + str(self.width)
        ppm_str = ppm_str + " "
        ppm_str = ppm_str + str(self.height)
        ppm_str = ppm_str + "\n"
        ppm_str = ppm_str + str(self.imax)
        ppm_str = ppm_str + "\n"
        for index in range(self.index_max):
            r = self.plane_r[index]
            g = self.plane_g[index]
            b = self.plane_b[index]
            if self.is_ascii:
                ppm_str = ppm_str + ('%3d %3d %3d ' % (r,g,b))
                if not ((1+index) % 6):
                    ppm_str = ppm_str + '\n'
            else:
                ppm_str = ppm_str + chr(r) + chr(g) + chr(b)
        return ppm_str


if __name__ == '__main__':

    p = ppm(400,400)
    # Spray bytes from stdin onto canvas.
    for ii in range (1, p.index_max):
        try:
            r = ord(sys.stdin.read(1))
            g = ord(sys.stdin.read(1))
            b = ord(sys.stdin.read(1))
            p.spray(r,g,b)
        except TypeError, e:
            # read(1) returned empty string.
            break

    # Dump the PPM file to stdout.
    sys.stdout.write(str(p))