python-3.x - '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'类型的异常发生参数不可迭代”。有没有另一种方法可以用来遍历我的面部照片的所有路径?还是我的代码有其他问题?
解决方案
所以我最初认为 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()
推荐阅读
- java - 为什么Java的数据结构实现扩展了另一个而不是有一个字段?
- python - 为什么我不能使用 for 循环从另一个列表中删除一个列表?
- ios - 使用 SwiftUI 在不同的 UI 层次结构之间切换的正确方法是什么?
- python - 如何在Python中调整像图像一样的矩阵大小
- python - numpy reshape 如何使用负变量作为第二个参数
- auth0 - 有没有办法通过 state 参数传递 redirect_uri 并在回调端点中访问所述参数?
- python - `signal.signal` 和 asyncio 的 `EventLoop.add_signal_handler` 之间的区别
- javascript - 在 Workbox 中重新验证策略时使用 Stale 进行预缓存
- matlab - 求解 6 个 ode 的系统 - 可变参数 -CLOSED
- javascript - jquery加载方法不加载站点脚本和css为什么?