ppm_binary.py
1 # The MIT License (MIT) 2 # 3 # Copyright (c) 2018 Scott Shawcroft for Adafruit Industries LLC 4 # 5 # Permission is hereby granted, free of charge, to any person obtaining a copy 6 # of this software and associated documentation files (the "Software"), to deal 7 # in the Software without restriction, including without limitation the rights 8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 # copies of the Software, and to permit persons to whom the Software is 10 # furnished to do so, subject to the following conditions: 11 # 12 # The above copyright notice and this permission notice shall be included in 13 # all copies or substantial portions of the Software. 14 # 15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 # THE SOFTWARE. 22 """ 23 `adafruit_imageload.pnm.ppm_binary` 24 ==================================================== 25 26 Load pixel values (indices or colors) into a bitmap and for a binary ppm, 27 return None for pallet. 28 29 * Author(s): Matt Land, Brooke Storm, Sam McGahan 30 31 """ 32 33 __version__ = "0.0.0-auto.0" 34 __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git" 35 36 37 def load(file, width, height, bitmap=None, palette=None): 38 """Load pixel values (indices or colors) into a bitmap and for a binary 39 ppm, return None for pallet.""" 40 41 data_start = file.tell() 42 palette_colors = set() 43 line_size = width * 3 44 45 for y in range(height): 46 data_line = iter(bytes(file.read(line_size))) 47 for red in data_line: 48 # red, green, blue 49 palette_colors.add((red, next(data_line), next(data_line))) 50 51 if palette: 52 palette = palette(len(palette_colors)) 53 for counter, color in enumerate(palette_colors): 54 palette[counter] = bytes(color) 55 if bitmap: 56 bitmap = bitmap(width, height, len(palette_colors)) 57 file.seek(data_start) 58 palette_colors = list(palette_colors) 59 for y in range(height): 60 x = 0 61 data_line = iter(bytes(file.read(line_size))) 62 for red in data_line: 63 # red, green, blue 64 bitmap[x, y] = palette_colors.index( 65 (red, next(data_line), next(data_line)) 66 ) 67 x += 1 68 69 return bitmap, palette