Python Challenge [11]

Continuing with all things PIL, we’re going to get a little evil.

Since we’ve realized that we can use urllib to avoid the step of separately downloading content from a site, we’ll stick with that.

Start with making our import declarations

from PIL import Image
import urllib,sys

Then we’ll use a neat function size() to grab the dimensions of the image. This might be useful for skimming websites for images in the future and finding some characteristics of the image independent of css restrictions imposed on it.

def get_image_dimensions():
	url = "http://huge:file@www.pythonchallenge.com/pc/return/cave.jpg"
	file = urllib.urlopen(url).read()
	jpg = Image.open(file)
	print jpg.size
get_image_dimensions()

As for the real solution…

def get_img():
	url = "http://huge:file@www.pythonchallenge.com/pc/return/cave.jpg"
	img = urllib.urlretrieve(url,'cave.jpg')
get_img()
img = Image.open('cave.jpg')
w,h = img.size[0], img.size[1]
print "Image info:",img.format, img.size, img.mode
new = Image.new(img.mode,(w//2, h))
for i in range(w*h):
    y, x = divmod(i, w)
    p = img.getpixel((x,y))
    if i%2: #even==info, odd==photo
        new.putpixel((x/2,y/2+h//2),p)
    else:
        new.putpixel((x/2,y/2),p)
new.save('11.jpg')