如何完成这个Python函数以保存在同一文件夹中?

3 投票
4 回答
3792 浏览
提问于 2025-04-11 19:28

我正在尝试写我的第一个真正的Python函数,让它做点实际的事情。我想实现的是搜索一个指定的文件夹,然后打开所有的图片,把它们合并在一起,做成一张电影条幅图。想象一下,就是把5张图片叠在一起,变成一张图片。

我现在有了这段代码,应该差不多可以用,但可能需要一些修改:

import os
import Image

def filmstripOfImages():

    imgpath = '/path/here/'
    files = glob.glob(imgpath + '*.jpg')

    imgwidth = files[0].size[0]
    imgheight = files[0].size[1]
    totalheight = imgheight * len(files)

    filename = 'filmstrip.jpg'
    filmstrip_url = imgpath + filename

    # Create the new image. The background doesn't have to be white
    white = (255,255,255)
    filmtripimage = Image.new('RGB',(imgwidth, totalheight),white)  
    row = 0
    for file in files:
        img = Image.open(file)

        left = 0
        right = left + imgwidth
        upper = row*imgheight
        lower = upper + imgheight
        box = (left,upper,right,lower)
        row += 1

        filmstripimage.paste(img, box)
    try:
        filmstripimage.save(filename, 'jpg', quality=90, optimize=1)
    except:
        filmstripimage.save(miniature_filename, 'jpg', quality=90)")

我该如何修改这段代码,让它把新的filmstrip.jpg保存在我加载图片的同一个文件夹里?而且可能还有一些缺失的部分或者错误,谁能给点建议?

相关问题: 如何从一个图片文件夹生成Python中的电影条幅图?

4 个回答

1

如果你不是在开玩笑的话,你的脚本有几个问题。例如,glob.glob() 这个函数会返回一个文件名的列表(这些是字符串对象,而不是图像对象),所以 files[0].size[0] 这个写法是行不通的。

1

我觉得如果你把你的 try 部分改成这样:

filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1)
2

这不是对你问题的直接回答,但可能会对你有帮助:

#!/usr/bin/env python
from PIL import Image

def makefilmstrip(images, mode='RGB', color='white'):
    """Return a combined (filmstripped, each on top of the other) image of the images.

    """
    width  = max(img.size[0] for img in images)
    height = sum(img.size[1] for img in images)
    
    image = Image.new(mode, (width, height), color) 
    
    left, upper = 0, 0
    for img in images:
        image.paste(img, (left, upper))
        upper += img.size[1]

    return image

if __name__=='__main__':
    # Here's how it could be used:
    from glob import glob
    from optparse import OptionParser

    # process command-line args
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="file",
                      help="write combined image to OUTPUT")

    options, filepatterns = parser.parse_args()
    outfilename = options.file
    
    filenames = []
    for files in map(glob, filepatterns):
        if files:
            filenames += files

    # construct image
    images = map(Image.open, filenames)    
    img = makefilmstrip(images)
    img.save(outfilename) 

举个例子:

$ python filmstrip.py -o output.jpg *.jpg

撰写回答