Search code examples
pythonpngjpeg

How to Convert JPEG to PNG in Python and Save to other directory


I am trying to convert image from jpg to png but not been able to save it in other directory.


Solution

  • from PIL import Image 
    import glob, os
    directory = "/your_path/"
    for infile in glob.glob("*.JPG"):
        file, ext = os.path.splitext(infile)
        im = Image.open(infile)
        rgb_im = im.convert('RGB')
        rgb_im.save(directory + file + ".png", "PNG")
    for infile in glob.glob("*.jpg"):
        file, ext = os.path.splitext(infile)
        im = Image.open(infile)
        rgb_im = im.convert('RGB')
        rgb_im.save(directory + file + ".png", "PNG") 
    for infile in glob.glob("*.JPEG"):
        file, ext = os.path.splitext(infile)
        im = Image.open(infile)
        rgb_im = im.convert('RGB')
        rgb_im.save(directory + file + ".png", "PNG")
    for infile in glob.glob("*.jpeg"):
        file, ext = os.path.splitext(infile)
        im = Image.open(infile)
        rgb_im = im.convert('RGB')
        rgb_im.save(directory + file + ".png", "PNG")
    

    you can use this code to save your file in other directory. This code saves the file with the same name in "your_path" directory