2017-07-24 75 views
0

我正在嘗試創建一個程序,將目錄中的任何圖像的大小調整爲299x299。然後,我想重命名該圖像並將其轉換爲jpeg,以便所有圖像將被命名爲0.jpg,1.jpg,2.jpg等。我還想將轉換後的文件移動到它們自己的目錄。在python中重命名,調整大小和移動圖像文件

我已經解決了它的大小調整部分。但是,當我添加重命名代碼時,即(index = 0,new_image.save)file_name,str(index),+「.jpg」和index + = 1)時,調整大小部分不再起作用。有沒有人有什麼建議?

這是我到目前爲止有:

#!usr/bin/python 

from PIL import Image 
import os, sys 

directory = sys.argv[1] 
for file_name in os.listdir(directory): 
     print ("Converting %s" % file_name + "...") 
     image = Image.open(os.path.join(directory, file_name)) 

     size = 299, 299 
     image.thumbnail(size, Image.ANTIALIAS) 

     w, h = image.size 

     new_image = Image.new('RGBA', size, (255, 255, 255, 255)) 
     new_image.paste(image, ((299 - w)/2, (299 - h)/2)) 

     index = 0 

     new_image_file_name = os.path.join(directory, file_name) 
     new_image.save(file_name, str(index) + ".jpg") 

     index += 1 

print ("Conversion process complete.") 
+0

尼斯。但是......你的問題是什麼? – agtoever

+0

我想知道如果有人有更好的建議,我怎麼能達到我的預期結果:) – lostInEncryption

回答

1

documentation

Image.save(fp, format=None, **params)

給定 的文件名保存此圖像。如果未指定格式,則可能的話,使用的格式由文件擴展名確定爲 。

image.save正確的語法是:

new_image.save(file_name, 'JPG') 

要移動一個文件,你可以使用shutil.move

import shutil 
shutil.move(file_name, 'full/path/to/dst/') # the second argument can be a directory 
+0

謝謝!但我的主要問題是如何按順序重命名文件,然後將它們移動到另一個目錄。 – lostInEncryption

+0

@lostInEncryption檢查我的編輯? –

相關問題