从一组图像尝试创建 GIF

5
我将使用Python来从一组PIL图像创建动画.gif。以下是我目前的代码:
from images2gif import writeGif
from PIL import Image, ImageDraw
import os
import sys
import random
import argparse
import webbrowser

filename = ""

def makeimages():
    for z in range(1, 31):
        dims = (400, 400)  # size of image
        img = Image.new('RGB', dims)  # crete new image
        draw = ImageDraw.Draw(img)
        r = int(min(*dims)/100)
        print "Image img%d.png has been created" % z

        n = 1000

        for i in range(n):
            x, y = random.randint(0, dims[0]-r), random.randint(0, dims[1]-r)
            fill = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            draw.ellipse((x-r, y-r, x+r, y+r), fill)

       img.save('.img%d.png' % z)

def makeAnimatedGif():
    # Recursively list image files and store them in a variable
    path = "./Images/"
    os.chdir(path)
    imgFiles = sorted((fn for fn in os.listdir('.') if fn.endswith('.png')))

    # Grab the images and open them all for editing
    images = [Image.open(fn) for fn in imgFiles]

    global filename
    filename = filename + ".gif"
    writeGif(filename, images, duration=0.2)
    print os.path.realpath(filename)
    print "%s has been created, I will now attempt to open your" % filename
    print "default web browser to show the finished animated gif."
    #webbrowser.open('file://' + os.path.realpath(filename))


def start():
    print "This program will create an animated gif image from the 30 images provided."
    print "Please enter the name for the animated gif that will be created."
    global filename
    filename = raw_input("Do Not Use File Extension >> ")
    print "Please wait while I create the images......"
    makeimages()
    print "Creating animated gif...."
    makeAnimatedGif()

start()

以下是错误信息:

Traceback (most recent call last):
  File "Final.py", line 60, in <module>
    start()
  File "Final.py", line 56, in start
    makeimages()
  File "Final.py", line 30, in makeimages
    img.save('Images/.img%d.png' % z)
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/usr/local/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 572, in _save
    ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageFile.py", line 481, in _save
    e = Image._getencoder(im.mode, e, a, im.encoderconfig)
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 401, in _getencoder
    raise IOError("encoder %s not available" % encoder_name)
IOError: encoder zip not available

希望的输出结果是让Python创建30个图像,将它们组合起来,然后将其保存为GIF文件。

1
请编辑您的代码,包括错误和追踪信息。谢谢! - Joseph Farah
我可以说通过全局变量传递参数是真正的代码异味吗?请不要这样做。 - Mark Ransom
哦,天啊。那是我的错,我会添加它们的。抱歉 :/ - user181895
@Mark Ransom,那有没有更合适的方式呢? - user181895
将信息作为实际参数传递到函数中。 - Mark Ransom
1个回答

2

你的代码中有一个错别字。应该是 img.save('.img%d.png' % z) 这一行需要缩进。

另外,你的代码主要问题是生成的图像不在你生成 gif 的目录下的 ./Images/ 中。

你需要确保 ./Images/ 目录在你的文件夹中存在。

下面的代码修复了这些问题,并且可以正常工作。

from images2gif import writeGif
from PIL import Image, ImageDraw
import os
import sys
import random
import argparse
import webbrowser

filename = ""


def makeimages():
    # Create the dir for generated images
    if not os.path.exists("Images"):
        os.makedirs("Images")
    for z in range(1, 31):
        dims = (400, 400)  # size of image
        img = Image.new('RGB', dims)  # crete new image
        draw = ImageDraw.Draw(img)
        r = int(min(*dims)/100)
        print "Image img%d.png has been created" % z

        n = 1000

        for i in range(n):
            x, y = random.randint(0, dims[0]-r), random.randint(0, dims[1]-r)
            fill = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
            draw.ellipse((x-r, y-r, x+r, y+r), fill)

        img.save('Images/.img%d.png' % z)

def makeAnimatedGif():
    # Recursively list image files and store them in a variable
    path = "./Images/"
    os.chdir(path)
    imgFiles = sorted((fn for fn in os.listdir('.') if fn.endswith('.png')))

    # Grab the images and open them all for editing
    images = [Image.open(fn) for fn in imgFiles]

    global filename
    filename = filename + ".gif"
    writeGif(filename, images, duration=0.2)
    print os.path.realpath(filename)
    print "%s has been created, I will now attempt to open your" % filename
    print "default web browser to show the finished animated gif."
    #webbrowser.open('file://' + os.path.realpath(filename))


def start():
    print "This program will create an animated gif image from the 30 images provided."
    print "Please enter the name for the animated gif that will be created."
    global filename
    filename = raw_input("Do Not Use File Extension >> ")
    print "Please wait while I create the images......"
    makeimages()
    print "Creating animated gif...."
    makeAnimatedGif()

start()

Generated Gif


尝试了上述方法,但仍然出现相同的错误。 - user181895
我将错误添加到了原帖中。 - user181895
3
新错误:TypeError:必须是字符串或缓冲区,而不是None - user181895
我发现了我的代码中似乎有问题的部分。在makeanamatedGif函数中,我定义filename = filename + ".gif"的方式是有问题的。当它尝试写入GIF时,它会将文件名参数视为空白。这就是导致TypeError: must be string or buffer, not None的原因。我一直在Ubuntu 15.04上进行所有操作,所以我会尝试使用第二个平台来确认。 - user181895
问题已经解决,感谢@Tim的帮助。感谢所有评论者提供的协助。结果发现是一个库的问题,我从github下载了新的库[链接] https://github.com/rec/echomesh/blob/master/code/python/external/images2gif.py - user181895
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接