我非常是Python的新手。我今天刚开始。
我正拼命地将图像保存到固定路径,例如:
/Users/myname/Sites/Tester/images/
因此,如果我有一个名为“ 1.jpg”的图像,它将被放置在这里:
/Users/myname/Sites/Tester/images/1.jpg
这是我的脚本:
from PIL import Image
import tempfile
def set_image_dpi(file_path):
im = Image.open(file_path)
length_x, width_y = im.size
factor = min(1, float(1024.0 / length_x))
size = int(factor * length_x), int(factor * width_y)
im_resized = im.resize(size, Image.ANTIALIAS)
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
temp_filename = temp_file.name
im_resized.save(temp_filename, dpi=(300, 300))
return temp_filename
但是,这会将文件保存在:
/var/folders/1n/hdyfv8z96v5_hcb9tsgvt7cr0000gn/T/tmp91rams5v.jpg
我该怎么办,它将保存在我指定的路径中?
"MY_PATH / temp_filename"
答案 0 :(得分:0)
这里不需要tempfile
模块,只需在调用.save()
时指定路径:
from PIL import Image
import os
def set_image_dpi(file_path, save_folder):
im = Image.open(file_path)
length_x, width_y = im.size
factor = min(1, float(1024.0 / length_x))
size = int(factor * length_x), int(factor * width_y)
im_resized = im.resize(size, Image.ANTIALIAS)
save_path = os.path.join(save_folder,'test.png')
# creates path: C:\Users\User\Pictures\test.png
im_resized.save(save_path, dpi=(300, 300))
set_image_dpi('test.png','C:\\Users\\User\\Pictures')
答案 1 :(得分:0)
我猜您的主要问题是从原始路径(诸如/where/images/are/taken/from/1.jpg
)和目标目录(/Users/myname/Sites/Tester/images/
)构建结果路径。 os.path
包中的方法可以提供帮助(请参见https://docs.python.org/3/library/os.path.html):
import os
dest_dir = '/Users/myname/Sites/Tester/images/'
...
base = os.path.basename(file_path) # this will be '1.jpg'
dest_path = os.path.join(dest_dir, base) # this will be the full path
im_resized.save(dest_path)
正如其他人在评论中说的那样,这里不需要tempfile
。