Can anyone show me how i can convert all png images in my local folder to jpg images? I've tried using the following code
path1 = r'C:\Users\david.han\Desktop\COPY_images_files'
path2 = r'C:\Users\david.han\Desktop\JPG converter'
files_to_convert = (f for f in os.listdir(path1) if f.endswith(".png"))
for filename in files_to_convert:
im = Image.open(os.path.join(path1, filename))
root, _ = os.path.splitext(filename)
jpg_file = os.path.join(path2, f'{root}.jpg')
im.save(jpg_file)
I keep getting this error "OSError: cannot write mode P as JPEG"
I've decided to keep JPG but in case anyone wants to know how to change png to jpg
enter code here
from PIL import Image
import os
path = r'C:\Users\david.han\Desktop\COPY_images_files'
for file in os.listdir(path):
if file.endswith(".jpg"):
img = Image.open(file)
file_name, file_ext = os.path.splitext(file)
img.save('/png/{}.png'.format(file_name))
Correction to David's code:
from PIL import Image
import os
path = r'enter_path_to_images'
for file in os.listdir(path):
if not file.endswith(".jpg"):
img = Image.open("{path}/{file}")
file_name, file_ext = os.path.splitext(file)
img.save('/png/{}.png'.format(file_name))
In this case, we also need to add the correct path not to get any errors.
Related
Support file
import pygame
from os import walk
def import_folder(path):
surface_list = []
for folder_name, sub_folders, img_files in walk(path):
for image_name in img_files:
full_path = path + '/' + image_name
image_surf = pygame.image.load(full_path)
surface_list.append(image_surf)
return surface_list
def import_folder_dict(path):
pass
I tried changing the image format to jpeg, which was previously png but that also didn't work out and I'm really confused to why this is happening.
Below is the error:
pygame.error: Unsupported image format
how can i get the file name without its root and path. only a name so i can save the images i want to convert with the same original name?
import sys
import os,glob
from PIL import Image, ImageFilter
path = os.getcwd()
if not os.path.exists('converted'):
save_to = os.makedirs('converted')
for i in glob.glob(f'{path}/*.jpg'):
img = Image.open(i)
img.save(???????) ######## <---------?????????
#i want to save the imege whith its original name,
# but with a different extention, and i want to save it to a different folder then cwd
Use os.path.basename to get filename without path.
Use os.path.splitext to split filename into stem and suffix.
Did you wanted something like this?
for i in glob.glob(f'{path}/*.png'):
img = Image.open(i)
basename = os.path.basename(i)
root_ext = os.path.splitext(basename)[0]
ext = ".png"
img.save(path+"/converted/" + root_ext + ext)
So I have been trying to iterate through a folder containing pictures, convert the pictures to a new format and save the new pictures into a new folder.
import sys
import os
from PIL import Image, ImageFilter
first_folder = sys.argv[1]
result = sys.argv[2]
if not os.path.exists(result):
os.makedirs(result)
for filename in os.listdir(first_folder):
img = Image.open(f'{first_folder}{filename}')
img.filter(ImageFilter.SHARPEN)
split =os.path.splitext(filename)[0]
img.save(f'{result}{split}.png', 'png')
print('Pictures Converted')
print ('all pictures in png format in the new folder')
when I run "python converter.py old_folder new_folder" I get this error message below
File "converter.py", line 18, in <module>
img = Image.open(f'{first_folder} {filename}')
File "C:\Users\scorpio\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\Image.py", line 2809, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'old_folderpic2.jpg'
you're missing folder separator, try this:
import sys
import os
from PIL import Image, ImageFilter
first_folder = sys.argv[1]
result = sys.argv[2]
if not os.path.exists(result):
os.makedirs(result)
for filename in os.listdir(first_folder):
img = Image.open(f'{first_folder}\{filename}')
img.filter(ImageFilter.SHARPEN)
split =os.path.splitext(filename)[0]
img.save(f'{result}\{split}.png', 'png')
print('Pictures Converted')
print ('all pictures in png format in the new folder')
I'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.
I've been doing some researches and came to this:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.
Do you guys have any idea for helping me going through the process?
You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png.
You should get the name of your jpg file and then use that to name and save the png file.
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted. Try the code with some copied images inside a test folder, before applying to the intended folder. All the best.
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.
I am generating a gif with images2gif from some .png pictures. I am using the following script:
__author__ = 'Robert'
from images2gif import writeGif
from PIL import Image
import os
file_names = sorted((fn for fn in os.listdir('/home/manager/Desktop/sf_linux_shared/project/prueba') if fn.endswith('.png')))
#['animationframa.png', 'animationframb.png', ...] "
images = [Image.open(fn) for fn in file_names]
size = (150,150)
for im in images:
im.thumbnail(size, Image.ANTIALIAS)
print writeGif.__doc__
filename = "my_gif.GIF"
writeGif(filename, images, duration=0.2)
however I have the following error:
IOError: [Errno 2] No such file or directory: 'cosa.png'
cosa.png is one of the pictures I want to create the gif with. The problem seems to be in:
images = [Image.open(fn) for fn in file_names]
but I cannot detect it
open(filename) looks in the current working directory if filename is not an
absolute path. The current working directory is the directory from which the script is run.
Either use os.chdir to change the working directory, or make all your filenames absolute:
WORKDIR = '/home/manager/Desktop/sf_linux_shared/project/prueba'
file_names = sorted((os.path.join(WORDIR, fn)
for fn in os.listdir(WORKDIR) if fn.endswith('.png')))