1

I've been playing around with Pythonista on iOS to create some automation scripts.

I have a problem where I'm trying to grab an animated gif from a remote url. I've come up with the following script.

import Image
from urllib import urlopen
from io import BytesIO

url = "http://someurl.com/funny.gif"
img = Image.open(BytesIO(urlopen(url).read()))

I get the image but it only appears to be the first frame of the gif? I'm guessing it has something to do with the BytesIO not reading in the whole file but I'm not sure?

Hope I'm along the right lines.

calabi
  • 283
  • 5
  • 18
  • I'd rather say it has to do with how you open and manipulate the image. What does it matter to the `urlopen`, what kind of URI it downloads, you would grab html and binary the same way? Try saving it as a file, and open with an external tool. – luk32 Jul 11 '14 at 00:09
  • It doesn't seem to be saving it as a gif this way? Maybe there is a different way I can read the file in? – calabi Jul 11 '14 at 00:19
  • 1
    Have you actually tried saving the file, not the image? You don't show any code for it. You just open the url and make an `Image` object out of it. – luk32 Jul 11 '14 at 00:31
  • I removed a line which is used for saving to the clipboard in pythonista for iOS.. It's clipboard.set_image(url) when I paste the image, it is only the first frame.. Also tested with a photos.save_image() but as stated these are specific to pythonista – calabi Jul 11 '14 at 00:43

2 Answers2

3

You're almost there. You use img.seek to advance frames. So..

import Image
from urllib import urlopen
from io import BytesIO
url = 'http://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif'

img = Image.open(BytesIO(urlopen(url).read()))

# Start with first frame
img.seek(0)
#img.show()

# Advance by one
img.seek(img.tell() + 1)
#img.show()

Here's a SO post showing how to save a gif using the Image class.

Community
  • 1
  • 1
machow
  • 1,034
  • 1
  • 10
  • 16
  • Is there a way to get another image object with only one frame? I'm having another issue that I believe is caused by the specific ways gifs are encoded and I think if I can extract the individual frames from the gif object it will fix it. (gifs have their transparency replaced with flat colours with rendered on a tkinter canvas, the thing is those colours change from gif to gif so I think it has to do with how each individual gif is encoded.) – TenDaysTillDallas Dec 29 '21 at 15:50
1

According to Pillow Manual:

To save all frames, the save_all parameter must be present and set to True.

So, opened image could be save by:

image.save('filename.gif', save_all=True)

Cybernick
  • 56
  • 4