code: def pack_rows(rows, bitdepth):
      
  
      assert bitdepth < 8
      assert 8 % bitdepth == 0
  
      # samples per byte
      spb = int(8 / bitdepth)
  
      def make_byte(block):
          """Take a block of (2, 4, or 8) values,
          and pack them into a single byte.
          """
  
          res = 0
          for v in block:
              res = (res << bitdepth) + v
          return res
  
      for row in rows:
          a = bytearray(row)
          # Adding padding bytes so we can group into a whole
          # number of spb-tuples.
          n = float(len(a))
          extra = math.ceil(n / spb) * spb - n
          a.extend([0] * int(extra))
          # Pack into bytes.
          # Each block is the samples for one byte.
          blocks = group(a, spb)
          yield bytearray(make_byte(block) for block in blocks)
docs: Yield packed rows that are a byte array.
      Each byte is packed with the values from several pixels.