PIL problem

bfrederi brfredericks at gmail.com
Wed Oct 8 11:10:02 EDT 2008


I am having a problem using PIL. I am trying to crop and image to a
square, starting from the center of the image, but when I try to crop
the image, it won't crop. Here are the relevant code snippets:

### Function I am testing ###
def create_square_image(file_name):
    """ Creates a thumbnail sized image and turns it into a square """
    image = Image.open(open(file_name))

    size_tuple = image.size
    width = size_tuple[0]
    height = size_tuple[1]

    square_length = 75

    x1 = (width / 2) - (square_length / 2)
    x2 = x1 + square_length
    y1 = (height / 2) - (square_length / 2)
    y2 = y1 + square_length

    image.crop((x1,y1,x2,y2))
    image.save(file_name, "JPEG")


### In my tests.py ###
def testCreateSquareImage(self):
    """ Test to turn image into a square """
    self.convert_file = '/home/bfrederi/square-dissertation.jpg'
    tkl_converter.create_square_image(self.convert_file)
    image = Image.open(self.convert_file)
    if image.size[0] == 75 and image.size[1] == 75:
        self.assert_(True)
    else:
        self.fail("Width: %s Height: %s" % (image.size[0],
image.size[1]))

### Test result ###
FAIL: Test to turn image into a square
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 462, in testCreateSquareImage
    self.fail("Width: %s Height: %s" % (image.size[0], image.size[1]))
AssertionError: Width: 75 Height: 97

----------------------------------------------------------------------

The image is unchanged. Anyone have any idea what I'm doing wrong?
I've tried opening the file, and outputting to a different file
(instead of overwriting the file), but the new file always comes out
the same as the original.



More information about the Python-list mailing list