我正在开发一个 Django 项目,用户上传图像,然后他们可以编辑 EXIF 数据并下载写入图像的编辑数据。
将数据写回图像时,我得到
TypeError: argument of type 'NoneType' is not iterable
工作起来相当复杂,但我会尽力抓住要点和相关代码。我必须将从表单接收到的数据转换为包含与 ExifTAG 代码相对应的keys() 的字典。
我现在正在遵循这个出色的指南https://blog.matthewgove.com/2022/05/13/how-to-bulk-edit-your-photos-exif-data-with-10-lines-of- python/ by Matthew Gove 将数据写回图像。
我可以成功创建 PILLOW_TAGS 列表和值(打印到控制台),并且我正在过滤任何
None
k/v
,所以很困惑为什么我会得到 TypeError: argument of type 'NoneType' is not iterable
任何帮助表示赞赏。
编辑 - 如果我“硬编码”PILLOW_TAGS 和 VALUES 列表,我不会收到 Nonetype 错误并且数据会被写入。例如,这不会给出 Nonetype 错误。
PILLOW_TAGS = [315, 33432,]
VALUES = ['foo', 'bar']
完整相关代码
PILLOW_TAGS = list(filter(None, image_exif_data_with_codes.keys()))
print("KEYS",PILLOW_TAGS)
VALUES = list(filter(None, image_exif_data_with_codes.values()))
print("values",VALUES)
pillow_img = PillowImage.open(image.image.path)
img_exif = pillow_img.getexif()
for tag, value in zip(PILLOW_TAGS, VALUES):
img_exif[tag] = value
for tag in PILLOW_TAGS:
try:
english_tag = ExifTags.TAGS[tag]
value = img_exif[tag]
except:
continue
print("{}: {}".format(english_tag, value))
pillow_img.save(image.image.path, exif=img_exif)
image.save()
回溯
File "C:\....\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\...\.venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\...\core\views.py", line 128, in test_view
pillow_img.save(image.image.path, exif=img_exif)
File "C:\...\.venv\lib\site-packages\PIL\Image.py", line 2439, in save
save_handler(self, fp, filename)
File "C:\...\.venv\lib\site-packages\PIL\JpegImagePlugin.py", line 777, in _save
exif = exif.tobytes()
File "C:\..\.venv\lib\site-packages\PIL\Image.py", line 3792, in tobytes
and ExifTags.IFD.Interop in value
TypeError: argument of type 'NoneType' is not iterable```
不要只过滤一个操作中的键,而只过滤另一个操作中的值——并期望能够重新组合这两个列表——而是一起过滤键和值,因此当您删除一个值时,您也会删除关联的键。
valid_image_data = dict(
(k,v)
for (k,v) in image_exif_data_with_codes.items()
if (k is not None) and (v is not None)
)
PILLOW_TAGS = valid_image_data.keys()
VALUES = valid_image_data.values()
这样你的列表就永远不会长度不等,导致
zip
插入 None
作为占位符(并且还会使索引不再对齐)。