如何使用 Python PIL 将图像保存到特定目录?

Posted

技术标签:

【中文标题】如何使用 Python PIL 将图像保存到特定目录?【英文标题】:How do I use Python PIL to save an image to a particular directory? 【发布时间】:2015-10-04 17:20:26 【问题描述】:

例如,我想处理一些图像,然后将其保存到特定目录。如何保存到我所在目录以外的特定目录? 我知道这将保存到我所在的目录:

from PIL import Image
""" Some Code """
img.save("sample.png", "")

如何保存到其他目录?

【问题讨论】:

您使用保存文件的完整路径,而不是相对路径 - C:/somefolder/yourfilehere.jpg 而不仅仅是 yourfilehere.jpg 【参考方案1】:

先创建目录再保存图片到目录

from PIL import Image
import os

image_path = "path/to/image"

os.mkdir(image_path)
image = image.save(f"image_path/image.png")

【讨论】:

【参考方案2】:

试试这个

img.save('/absolute/path/to/myphoto.jpg', 'JPEG')

【讨论】:

不是OP,但感谢您的回答。我对img 的对象有点困惑。 OP 导入了Image,但似乎没有使用它,或者只是没有透露它。哪些对象可以调用.save()函数? @Bowen Liu img 似乎是Image 类的一个实例,它具有.save() 函数。见pillow.readthedocs.io/en/stable/reference/Image.html

以上是关于如何使用 Python PIL 将图像保存到特定目录?的主要内容,如果未能解决你的问题,请参考以下文章