问题描述
下面是我用来将二进制数据转换为图像然后保存的代码
img = base64.b64decode(rec.image3)
img_conv = Image.open(io.BytesIO(img))
img_format = img_conv.format
img_conv.save('{}/{}'.format(path,rec.image_name),format(img_format))
有 4 张具有相同代码的图像,我想处理如果所有文件名在同一位置都相同的情况,即使它有重复的名称,也应该强制保存 4 张图像。
任何建议将不胜感激。谢谢。
解决方法
假设您想将每个文件保留在不同的名称下:只要目录中存在具有此类名称的文件,就将“_”附加到原始文件名。
from pathlib import Path
path_to_save = Path(path,rec.image_name)
while path_to_save.exists():
path_to_save = Path(str(path_to_save) + '_')
img_conv.save(path_to_save,format(img_format))