1

I would like to cut an image into 12 equal boxes, because the Instagram mobile app shows a 3x4 table. In resume, I want to automate a Image Cutter to make mosaics at Instagram. I downloaded Pillow's library.

This is the code that I have written:

from PIL import Image

img = Image.open("Koala.jpg")

x,y = img.size  #assign x,y to image's valors
a = round(x/3)  #widht   
b = round(y/4)   #height

img2 = img.crop((0,0,a,b))  #assing variable img2 to the first box    
img2.save("img2.jpg")       #save the first box

img3 = img.crop((a,0,a,b))   #assign variable img3 to the box next to img2    
img3.save("img3.jpg")        #save

img4 = img.crop((2*a,0,a,b)) #same process
img4.save("img4.jpg")

I think that would be easy using a loop. Sorry, I'm a noob and this is my first script in python.

1
  • So - just note that nothing in Python requires variable letters to have a single letter. It makes no sense writting a = round(x/3) #widht to remind you and other people vieing the code that a contains the widthwhen you can simply use width and height as variable names themselves.
    – jsbueno
    Commented Jul 13, 2015 at 17:19

1 Answer 1

2

Yes, simply use a double for loop,

for i in range(3):
    for j in range(4):
        img_tmp = img.crop((i*a, j*b, (i+1)*a, (j+1)*b)) 
        img_tmp.save("img_{}_{}.jpg".format(i, j))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.