[Tutor] Trying to use the Pillow library to create a gif

Alan Gauld alan.gauld at btinternet.com
Tue Nov 18 11:04:50 CET 2014


On 18/11/14 09:24, Jason Y wrote:
> With these images, I'm attempting to create a gif by resizing an image
> (a 001.jpg) 10 times and than use a recursive function that should use
> the next image (a 002.jpg) and resize that 10 times, etc...; until it
> reaches "a 721.jpg", where it should stop.

Don't use recursion for this, use a loop.

Recursion is great for some things in python but its not great
as a loop substitute for more than a few items. You are likely
to run into memory limits using recursion. Use a loop when you
want to repeat things. And from your description, a while loop
looks like the right choice:

while nextNumber < 721:  # maybe?



> I'm also sure there are plenty of errors or inefficiency in this code.
> This will run; however, it will not go on to the next image. I've tried
> a few things to manipulate the string "a 001.jpg".
> Anyone?
>
> from PIL import Image
> s = ("a 001.jpg")
> im = Image.open(s)
> def main(im):

Use a more meaningful function name then call that function
from main() if you feel you must have a main().
Its not compulsory though, but meaningful function names
make the code more readable and reusable.

>      try:
>          x = 920
>          y = 80
>          for a in range(0,10):
>              x += 100
>              y += 100
>              box = (x,y)
>              im = im.resize(box)
>              im.show()
>          s = list(s)

You don;t need to convert the string to a list, you can access the 
characters by indexing just like you do with lists.

>          if s[4] < 9:
>              s[4] = int(s[4]) + 1

Notice that you are replacing a character with a number.

>          elif s[4] == 9:
>              s[4] = 0
> s[3] = int(s[3]) + 1
>          elif s[3] < 9:
> s[3] = int(s[3]) + 1
>          elif s[3] == 9:
>              s[3] = 0
> s[2] = int(s[2]) + 1
>          elif s[2] < 9:
> s[2] = int(s[2]) + 1
>          elif s[2] == 9:
>              s[2] = 0
>          s = ''.join(s)

You camn't join numbers in a string.
This would throw a TypeError but you can't see it because
you've hidden your errors, see below...

However, you can probably replace all of that using slices

nextNumber = int(s[2:5]) + 1
nextFile = s[:2]+str(nextNumber)+s[5:]

>          im = Image.open(s)
>          return main(im)

see above re using a while loop rather than recursion.

>      except:
>          return -1

Don't do this. It hides every error message. You have no
idea why your code fails because you can't see the cause
of failure. That's a bad thing.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my phopto-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list