1

I'm trying to make a program that gets an image from URL. It returns first frame of the gif if the image is animated and just an image if it's not animated.

Code:

def is_animated(im):
    try:
        im.seek(1)
        return True
    except EOFError:
        return False

def getImg(url):
    img = Image.open(requests.get(url, stream=True).raw, mode='r')
    if is_animated(img):
        return img
    else:
        print('no animation detected')
        return img

Problem: I tried it with an animated picture: it returned True in is_animated(), but it doesn't return an Image object in return img. Errors logs are blank. What can be the problem here? I will appreciate any help, thank you in advance.

JoshJohnson
  • 181
  • 3
  • 18

1 Answers1

3

seek doesn't return anything in Pillow. It just seeks to the next frame, and points the img object to that frame, so if you output img, it'll show that next frame.

Also, this means that by running im.seek(1) in is_animated, you're automatically seeking to the next frame, meaning you'll never return the first image in the sequence from your getImg function. You'd have to run im.seek(0) in order to return the first frame.

Source: the source code (note how nothing is returned in seek or _seek)

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • Ok, thank you for the tip. However it still doesnt output Image object – JoshJohnson Feb 17 '21 at 16:56
  • @JoshJohnson It's not really clear what you mean by `it still doesnt output Image object`. How are you trying to output it? You're doing `return img` now, which seems correct, but it's now not clear how you're trying to output it, since you haven't included the relevant code for that. – Random Davis Feb 17 '21 at 17:11
  • I've updated the code, I've tried running it with non-animated picture and it worked perfectly. – JoshJohnson Feb 17 '21 at 17:15
  • @JoshJohnson your update wasn't really helpful, since it wasn't what I asked for, which is how you're trying to output the image. Also you're still seeking the image via `is_animated`, so you're always going to return the second frame, unless you run `im.seek(0)` after running `im.seek(1)`. – Random Davis Feb 17 '21 at 17:17
  • @JoshJohnson also have you tried other animated images? Have you tried saving one to your disk and then loading it directly to see if that changes anything? Have you looked at online examples of people using `seek` to output animated images? – Random Davis Feb 17 '21 at 17:21
  • Thank you so much for your answer, it cleared some misunderstandings – JoshJohnson Feb 17 '21 at 17:37