''' Solution to Problem 9. ''' from PIL import Image def legal( v ) : # if v is negative, return 0, and if it's over 255, return 255. Otherwise, return itself if v < 0: return 0 elif v > 255: return 255 else: return v def offset( pixel, x, y, z ) : r, g, b = pixel nr, ng, nb = r - x, g - y, b - z nr, ng, nb = legal(nr), legal(ng), legal(nb) npixel = (nr, ng, nb) return npixel def shift( original, x, y, z ) : ow, oh = original.size # get dimensions of original nw, nh = ow, oh # determine dimensions of new image new_image = Image.new('RGB', (nw, nh)) # create new image for nx in range(0, nw): # fill in every pixel of new image for ny in range(0, nh): nspot = (nx, ny) # set spot to be filled in new image ospot = nspot # determine corresponding spot in original opixel = original.getpixel(ospot) # get pixel (color) at corresponding spot npixel = offset(opixel, x, y, z) # determine pixel (color) for new image new_image.putpixel(nspot, npixel) # set spot in new image return new_image # return filled in new image if ( __name__ == '__main__' ) : import url link = 'http://www.cs.virginia.edu/~cs1112/images/ml.png' original = url.get_image( link ) try : print( legal( -1 ), legal( 125 ), legal( 256 ) ) except : print( 'legal() blows up' ) try : print( offset( ( 25, 0, 200 ), 25, -50, 75 ) ) except : print( 'offset() blows up' ) try : im = shift( original, 25, -50, 75 ) im.show() except : print( 'shift() blows up' )