Hi guys,

i have a problem here

i have a situation where i need to save all the images opened using PIL
I have no idea how to do without displaying images on screen one by one and saving them
Can anyone please help how to save them without switching on the screen


Thanks...

Dani AI

Generated

You do not need to display images to save them with PIL/Pillow. Once you keep references to the opened Image objects (you already store them in self.imageInfo), you can batch-write them to disk in a single pass, optionally choosing a format and output folder just once.

Example: save all currently loaded images to a directory, auto-converting when needed (e.g., JPEG cannot handle RGBA/P modes).

import os
from tkFileDialog import askdirectory

def save_all_images(self, default_ext="png"):
    out_dir = askdirectory(title="Choose output folder")
    if not out_dir:
        return
    os.makedirs(out_dir, exist_ok=True)

    ext = default_ext.lower()
    fmt = "JPEG" if ext in ("jpg", "jpeg") else ext.upper()

    for idx, info in enumerate(self.imageInfo):
        im = info["im"]
        if fmt == "JPEG" and im.mode not in ("RGB", "L"):
            im = im.convert("RGB")  # avoid "cannot write mode RGBA as JPEG"

        # Use original name if you stored it; else generate one
        base = os.path.splitext(os.path.basename(info.get("path", f"image_{idx:03d}")))[0]
        out_path = os.path.join(out_dir, f"{base}.{ext}")
        im.save(out_path, fmt)

Practical tips:

  • If you want original names, store the source path when adding images: newImageData["path"] = imageName.
  • Relying on the file extension is enough; you usually do not need to pass format if the extension is recognized.
  • Avoid getdata() unless you actually use it; it duplicates pixel data and increases memory.

Docs: Pillow’s Image.save behavior and supported formats are detailed in Image.save and Image file formats.

Recommended Answers

All 7 Replies

You don't need to display them, if you maintain a list of the image objects open, you can easilly save them all in a nice loop.

Show a example of what you mean, I'll help you.

Cheers and Happy coding

You don't need to display them, if you maintain a list of the image objects open, you can easilly save them all in a nice loop.

Show a example of what you mean, I'll help you.

Cheers and Happy coding

Thank u for reply
here is the code for one image

def saveImage(self):
self.refreshImage()

name = asksaveasfilename(filetypes = [("Tif file",".tiff"),("Bmp file", ".bmp"),("Jpeg", '.jpeg'),("Gif",'*.gif')])

if name == "":
return

ext = name[name.rfind('.')+1:]
ext = ext.upper()

try:
self.curIm.save(name, ext)
except:
from tkMessageBox import showerror
showerror("Save error", "Save failed! Did you include a valid extension? (tiff, bmp, jpeg, gif, etc.)\ne.g. 'myimage1.tiff' and not just 'myimage1'.")

First wrap your code with Code-tags. You can do it easilly by selecting your code and clicking the code button.

And that code is useless mate. I mean you to show the code you use to open them.

And imports are done at the beginning of the script and never inside a function.

Cheers and Happy coding

Sorrry here is the code for open image

def addImage(self, imageName):
    try:
        newImageData = {}
        im = Image.open(imageName)
        data = im.getdata()
        width, height = im.size
    except IOError:
        from tkMessageBox import showerror
        showerror( "File Error", "The selected file could either opened or converted." )
        return

    newImageData['im'] = im
    newImageData['data'] = data
    newImageData['width'] = width
    newImageData['height'] = height
    newImageData['id'] = -1
    newImageData['contours'] = []
    newImageData['dots'] = []
    newImageData['landmarks'] = []
    newImageData['linewidth'] = 1
    newImageData['linelength'] = 20
    newImageData['stack'] = self.getCurrentStack()
    self.imageInfo.append(newImageData)[/CODE]

here is the imports related to that

import os
import re
import sys
from os.path import dirname, exists, normpath
import time

from Tkinter import *
import _anglesmodule
import Image
import ImageTk
import ImageDraw
import numpy
import math
import Tkinter
import Pmw
import ImageDraw
from SmartCounter import SmartCounter
from ListManager import BasicList
from xml_parser import get_xml_tree, build_xml_data
sys.path.insert(0, "../../..")
sys.path.insert(0, "../..")
from pcty.client.forms.SafeDialog import asksaveasfilename, askopenfilename
from tkFileDialog import askdirectory
import math
import cProfile
import pstats
from CalculateImageData import CalculateImageData
from VarRadioSelect import VarRadioSelect

from vertexMath import HandleRegTrans, HandleRegOff, HandleRegRot, HandleVertTrans, \
                        HandleVertRot, HandleVertScale, scale, HandlePointRot, \
                        HandleRotateAxis, createMatrix, computeTopRight, computePoint,\
                        HandleVertexScale, HandleVertexTrans
from imageUtils import rgb_map, color_to_byte, byte_to_rgb, expand_alpha, \
                        make_binary_mask, update_image_with_mask, threshold_image, \
                        top_regions, color_regions
import pcty.server.region_detect as region_detect
import copy
from ImageCylinder import ImageCylinder

histogramHeight = 128


try:
    from client.OpenMesh.Images import ImageStack
except:
    import sys
    sys.path.insert(0,"../../..")
    sys.path.insert(0,"../../MglToolsLibWin")
    sys.path.insert(0, "../../..")
    sys.path.insert(0, "../..")
    from client.OpenMesh.Images import ImageStack

First wrap your code with Code-tags. You can do it easilly by selecting your code and clicking the code button.

And that code is useless mate. I mean you to show the code you use to open them.

And imports are done at the beginning of the script and never inside a function.

Cheers and Happy coding

here is the code for saving current selected image

def saveImage(self):
        self.refreshImage()

        name = asksaveasfilename(filetypes = [("Tif file",".tiff"),("Bmp file", ".bmp"),("Jpeg", '.jpeg'),("Gif",'*.gif')])

        if name == "":
            return

        ext = name[name.rfind('.')+1:]
        ext = ext.upper()
        
        try:
            self.curIm.save(name, ext)
        except:
            from tkMessageBox import showerror
            showerror("Save error", "Save failed!  Did you include a valid extension?  (tiff, bmp, jpeg, gif, etc.)\ne.g. 'myimage1.tiff' and not just 'myimage1'.")

Sorrry here is the code for open image

def addImage(self, imageName):
        try:
            newImageData = {}
            im = Image.open(imageName)
            data = im.getdata()
            width, height = im.size
        except IOError:
            from tkMessageBox import showerror
            showerror( "File Error", "The selected file could either opened or converted." )
            return

        newImageData['im'] = im
        newImageData['data'] = data
        newImageData['width'] = width
        newImageData['height'] = height
        newImageData['id'] = -1
        newImageData['contours'] = []
        newImageData['dots'] = []
        newImageData['landmarks'] = []
        newImageData['linewidth'] = 1
        newImageData['linelength'] = 20
        newImageData['stack'] = self.getCurrentStack()
        self.imageInfo.append(newImageData)

here is the imports related to that

import os
import re
import sys
from os.path import dirname, exists, normpath
import time

from Tkinter import *
import _anglesmodule
import Image
import ImageTk
import ImageDraw
import numpy
import math
import Tkinter
import Pmw
import ImageDraw
from SmartCounter import SmartCounter
from ListManager import BasicList
from xml_parser import get_xml_tree, build_xml_data
sys.path.insert(0, "../../..")
sys.path.insert(0, "../..")
from pcty.client.forms.SafeDialog import asksaveasfilename, askopenfilename
from tkFileDialog import askdirectory
import math
import cProfile
import pstats
from CalculateImageData import CalculateImageData
from VarRadioSelect import VarRadioSelect

from vertexMath import HandleRegTrans, HandleRegOff, HandleRegRot, HandleVertTrans, \
                        HandleVertRot, HandleVertScale, scale, HandlePointRot, \
                        HandleRotateAxis, createMatrix, computeTopRight, computePoint,\
                        HandleVertexScale, HandleVertexTrans
from imageUtils import rgb_map, color_to_byte, byte_to_rgb, expand_alpha, \
                        make_binary_mask, update_image_with_mask, threshold_image, \
                        top_regions, color_regions
import pcty.server.region_detect as region_detect
import copy
from ImageCylinder import ImageCylinder

histogramHeight = 128


try:
    from client.OpenMesh.Images import ImageStack
except:
    import sys
    sys.path.insert(0,"../../..")
    sys.path.insert(0,"../../MglToolsLibWin")
    sys.path.insert(0, "../../..")
    sys.path.insert(0, "../..")
    from client.OpenMesh.Images import ImageStack

Your import concept mate is totally wrong. You should read a good python tutorial.

Back to the code, something like

self.image_list = []

def addImage(self, imageName):
        try:
            newImageData = {}
            im = Image.open(imageName)
            data = im.getdata()
            width, height = im.size
            self.image_list.append(imageName)
        except IOError:
            showerror( "File Error", "The selected file could either opened or converted." )
            return

        newImageData['im'] = im
        newImageData['data'] = data
        newImageData['width'] = width
        newImageData['height'] = height
        newImageData['id'] = -1
        newImageData['contours'] = []
        newImageData['dots'] = []
        newImageData['landmarks'] = []
        newImageData['linewidth'] = 1
        newImageData['linelength'] = 20
        newImageData['stack'] = self.getCurrentStack()
        self.imageInfo.append(newImageData)

You can then use the image_list something like...

for image in self.image_list:
    ...

Cheers and Happy coding

hey thanks for ur reply , i got it
we just have to say im.save

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.