Imagine Python - Image.Show (Page 3 of 4 )
You're probably wondering what all the image.show() calls are about; show() just creates a temporary image and opens it. This way we can see what's happening to our image step by step!
Anyway let's just slip off topic for a second here and imagine that you're in charge of some online art gallery/community where members can upload images and have them displayed for the world to see. As part of the site's design every image has a square thumbnail that links to the full-sized image.
We can think of this as a few steps:
- Loading the image and passing it to our function.
- Cropping our image so we end up with a square.
- Resizing (100 x 100) and saving our thumbnail.
#!/usr/bin/env python
import Image
def thumb(image):
size = list(image.size)
size.sort()
image = image.crop((0, 0, size[0], size[0]))
image = image.resize((100, 100), Image.ANTIALIAS)
return image
if __name__ == '__main__':
image = Image.open('sample1.jpg')
image = thumb(image)
image.save('sample2.jpg')
This really just defines a new user function named thumb() which we can then use to create our thumbnails! It starts by converting the images size to a list and sorting it in place so we have the smallest dimension at the beginning of the list (this value is then used while cropping our image). The next part then crops and resizes our image using the ANTIALIAS filter (better quality) before returning the new image.
Watermarking
Next up we're going to do some watermarking and paste a smaller graphic onto our image. Which as far as I know makes this the only example of watermarking with PIL, even though once again this is incredibly easy!
#!/usr/bin/env python
def watermark(image, thumb):
imageX, imageY = image.size
thumbX, thumbY = thumb.size
if thumbX < imageX and thumbY < imageY:
point1 = imageX - (thumbX + 10)
point2 = imageY - (thumbY + 10)
point3 = imageX - 10
point4 = imageY - 10
image.paste(thumb, (point1, point2, point3, point4))
if __name__ == '__main__':
import Image
image = Image.open('sample.jpg')
thumb = Image.open('thumb.jpg')
watermark(image, thumb)
image.show()
Quite proud of this for some reason; maybe because I've finally got my head around placing things where I want them on an image. Anyway what it is actually saying is that if 'thumb' is smaller than our image, then put it 10 pixels in from the bottom right hand corner of 'image' (since it would look pretty messed up in most cases otherwise).
Next: Lock It Down >>
More Python Articles
More By Mark Lee Smith