Python PIL将最后一张图片保存在内存中

时间:2018-09-25 20:58:31

标签: python python-3.x python-imaging-library

在我的代码中,我循环遍历一个csv文件,并针对每一行基于其中一个值分配一个图像,就像这样:

if 'V,S,M' in s.com:
    compic = Image.open('Com-VSM.png')
elif "V,S" in s.com:
    compic = Image.open('Com-VS.png')
elif "V,M" in s.com:
    compic = Image.open('Com-VM.png')
elif "S,M" in s.com:
    compic = Image.open('Com-SM.png')
elif "V" in s.com:
    compic = Image.open('Com-V.png')
elif "S" in s.com:
    compic = Image.open('Com-S.png')
elif "M" in s.com:
    compic = Image.open('Com-M.png')

但是,我注意到有时python会保留上一个循环中使用的图像,因此,如果List [1]使用'Com-M.png',而List [2]使用'Com-S.png',则结果是在制作图像时,List [2]将在如何解决此问题的任何猜测上将'Com-S.png'叠加在'Com-M.png'上吗?

完整循环(垃圾收集器是试图严重清除内存的尝试):

for s in L:
    scho = 0

    if 'Necromancy' in s.school:
        scho = necromancy
    elif 'Abjuration' in s.school:
        scho = abjuration
    elif 'Conjuration' in s.school:
        scho = conjuration
    elif 'Divination' in s.school:
        scho = divination
    elif 'Evocation' in s.school:
        scho = evocation
    elif 'Enchantment' in s.school:
        scho = enchantment
    elif 'Illusion' in s.school:
        scho = illusion
    elif 'Transmutation' in s.school:
        scho = transmutation
    else:
        scho = abjuration

    compic = 0
    font = ImageFont.truetype("Livingst.ttf", 48)


    #region Components
    if 'V,S,M' in s.com:
        compic = Image.open('Com-VSM.png')
    elif "V,S" in s.com:
        compic = Image.open('Com-VS.png')
    elif "V,M" in s.com:
        compic = Image.open('Com-VM.png')
    elif "S,M" in s.com:
        compic = Image.open('Com-SM.png')
    elif "V" in s.com:
        compic = Image.open('Com-V.png')
    elif "S" in s.com:
        compic = Image.open('Com-S.png')
    elif "M" in s.com:
        compic = Image.open('Com-M.png')
    else:
        compic = Image.open('Com-VSM.png')
    #endregion

    image_copy = scho.image
    image_copy.paste(compic, scho.point5, compic)
    imgpath = 's.name + '.png'
    image_copy.save(imgpath)
    del compic
    gc.collect()

1 个答案:

答案 0 :(得分:0)

在您的if ... elif ...中,您忘记了else语句。因此,如果不满足任何条件,则不会在每个循环中都设置 compic 变量。

您需要添加一个else语句来检查所有情况。

如果您没有空手,最好的做法是举起NotImplementedError,例如:

if 'V,S,M' in s.com:
    compic = Image.open('Com-VSM.png')
elif "V,S" in s.com:
    compic = Image.open('Com-VS.png')
elif "V,M" in s.com:
    compic = Image.open('Com-VM.png')
elif "S,M" in s.com:
    compic = Image.open('Com-SM.png')
elif "V" in s.com:
    compic = Image.open('Com-V.png')
elif "S" in s.com:
    compic = Image.open('Com-S.png')
elif "M" in s.com:
    compic = Image.open('Com-M.png')
else:
    raise NotImplementedError(s.com)

这样,更容易找到失踪案件