""" image.py, by chaynes@indiana.edu A PIL.Image module wrapper for CSCI A201. """ import PIL.Image def read(file_name): """Read an image from the named file and return it as a matrix of (r,g,b) pixel tuples, or raise 'Bad image type' if it is not a suitable image type. JPEG is a suitable type, while GIF and PNG are not. """ def make_matrix(lst, numCols): matrix = [] for i in range(0, len(lst), numCols): matrix.append(lst[i : i+numCols]) return matrix WIDTH_INDEX = 0 im = PIL.Image.open(file_name) imageData = list(im.getdata()) if not isinstance(imageData[0], tuple) or not len(imageData[0]) == 3: raise 'Bad image type', file_name return make_matrix(imageData, im.size[WIDTH_INDEX]) def new(matrix): """Return an image object made from the (r,g,b) pixel tuples in matrix. Two image object methods: show() displays the image in a window save(str) saves the image in a jpeg file named by the string """ def flatten_matrix(matrix): width = len(matrix[0]) lst = [] for index in range(len(matrix)): row = matrix[index] if width != len(row): raise 'Matrix is ragged (rows not all of the same length)' lst = lst + row return lst width = len(matrix[0]) height = len(matrix) im = PIL.Image.new('RGB', (width, height)) im.putdata(flatten_matrix(matrix)) return im