首页 > 解决方案 > 'Image' 类型的参数不可迭代

问题描述

我需要使用其中包含 jpg 图像的 mugshot["path"] 打开一个目录。找到图像后,我会调整它们的大小并使用 copyfile 复制它们。我添加的注释是从 print 方法打印出来的。这是我的代码。

        for mugshot in self.mugshots:
                print("mugshot is: ", mugshot) # prints {'path': '/leds/files/2021/1000000580', 'name': 'IN202100005_R.jpg'}

                try:
                    if self.mugshots_folder:
                        path = copyfile.join(self.afis_export_connection_string, self.mugshots_folder, mugshot["name"])
                    else:
                        path = copyfile.join(G.global_settings[(agenciesid, "afis_mugshot_export_connection_string")],
                                             mugshot["name"])
                    try:
                        with open(mugshot["path"], 'rb') as mugshot1:
                            im = Image.open(mugshot1)
                            print("im is=", im) # im is= <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2560x1080 at 0x7F0218F7C668>
                            print("im type is=", type(im)) # im type is= <class 'PIL.JpegImagePlugin.JpegImageFile'>
                            newsize = (480, 600)
                            im1 = im.resize(newsize)
                            print("im1 after resize is: ", im1) #im1 after resize is:  <PIL.Image.Image image mode=RGB size=480x600 at 0x7F0218F74C18>
                            temp = tempfile.TemporaryFile()
                            print("temp is: ", temp) #temp is:  <_io.BufferedRandom name=14>
                            im1.save(temp, format="JPEG")
                            print("im1.save ran") #im1.save ran
                            temp.seek(0)

                            copyfile.copyfile(im1, path) # params are (source, destination)
                            print("copyfile.copyfile ran") #this doesn't get printed
                            temp.close()

                    except Exception as e:
                        print("exception occurred ", e)

我得到“'Image'类型的异常发生参数不可迭代”。有没有另一种方法可以用来遍历我的面部照片的所有路径?还是我的代码有其他问题?

标签: python-3.x

解决方案


所以我最初认为 copyfile.copyfile 是 shutil.copyfile 但事实并非如此。这里的复制文件实际上是另一个创建的自定义函数,直到今天晚些时候我才发现。此函数采用特殊字符进行路径处理,这会导致其他问题。一些小改动后的工作代码

with open(mugshot["path"], 'rb') as mugshot_to_resize:
                        img = Image.open(mugshot_to_resize)
                        new_size = (480, 600)
                        image_resize = img.resize(new_size)
                        temp = tempfile.NamedTemporaryFile()
                        image_resize.save(temp, format="JPEG")
                        temp.seek(0)
                        copyfile.copyfile(temp.name, path)
                        temp.close()

推荐阅读