raster (PIL)

Diez B. Roggisch deets at nospam.web.de
Thu Jul 23 07:47:45 EDT 2009


superpollo wrote:

> hi.
> 
> i wrote a program which transforms a string of zeroes ando ones into a
> png file.
> 
> #!/usr/bin/env python
> import Image
> import sys
> bits_in_a_byte = 8
> raster_string = """\
> 00000000000000000000000000000000
> 00100100111100100000100000111100
> 00100100100000100000100000100100
> 00111100111000100000100000100100
> 00100100100000100000100000100100
> 00100100111100111100111100111100
> 00000000000000000000000000000000
> 00000000000000000000000000000000
> 00000000111100100000111100000000
> 00000000100000100000100100000000
> 00000000100000100000111100000000
> 00000000100000100000100000000000
> 00000000111100111100100000000000
> 00000000000000000000000000000000
> """
> raster_lines = raster_string.splitlines()
> high = len(raster_lines)
> wide = len(raster_lines[0])
> bytes_in_a_row = wide/bits_in_a_byte

This will give you the wrong result if not divideable by bits_in_a_byte. 

> bitmap = ""
> for raster_line in raster_lines:
>      for byte_count in range(bytes_in_a_row):
>          first_bit = byte_count*bits_in_a_byte
>          bitmap +=
> chr(int(raster_line[first_bit:first_bit+bits_in_a_byte] , 2))
> im = Image.fromstring("1", (wide , high) , bitmap)
> im.save(sys.stdout , "PNG")
> 
> any suggestions for improvement?

Instead of 

res = ""
for ...:
    res += ...

use 

res = []
for ...:
    res.append(...)

"".join(res)

There are some optimizations for the +=-op on strings, but I'm not sure how
far they go, and the other form is safer.

Diez



More information about the Python-list mailing list