How do I save images with custom names using PIL?

Viewed 716
from PIL import ImageGrab


payloadimage = ImageGrab.grabclipboard()

payloadimage.save('/path/to/image/imagename.jpg', 'JPEG')

I need to change the name every time this chunk of code is run. In order to do that the name needs to be saved as a variable. However, how do I do this considering I have a path to the folder which I'm trying to save the name to?

2 Answers

You can use these lines of code:

from PIL import Image  
import PIL  
      im1 = Image.open(r"C:\path\to\image\imagename.jpg ")  
      im1 = im1.save("custom_name.jpg") 

If you don't have a list of names, You can simply use number in a loop like:

for i in range(5):
    payloadimage.save('/path/to/image/imagename_'+str(i)+'.jpg', 'JPEG')

File names will be:

/path/to/image/imagename_0.jpg
/path/to/image/imagename_1.jpg
/path/to/image/imagename_2.jpg
/path/to/image/imagename_3.jpg
/path/to/image/imagename_4.jpg

But if you do have a list of names (dtype:string), say list_a, you can use:

for i in list_a:
    payloadimage.save('/path/to/image/imagename_'+i+'.jpg', 'JPEG')
Related