Converting all files (.jpg to .png) from a directory in Python - python

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.

Related

How can I read image name from a specific folder?

I want read image name like flower.png unnamed.png. Is there any way that I can read all images images one by one like we can read text file with open ("data.txt", "r") as myfile:
data = myfile.read().splitlines().. Hope you will give me a solution
thanks
enter code here from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.img'):
im=Image.open(filename)
image_list.append(im)
If you want to get all file name from a folder, you can use os.listdir
import os
filename = os.listdir("YOUR_FOLDER_NAME")

Convert PNG images from folder to JPG - Python

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.

Saving images as thumbnails Python

I have this code, it origionally comes from here: renaming files base on the file structure
I added a thumbnail save as to the function from here: Create thumbnail images for jpegs with python
I'm trying to select all files from a directory structure, rename them based on the file structure. I've added a filter using 'in', but I can't get the resize as thumbnail bit to work.
Name Image is not defined.
import os
import shutil
#testing
import sys
import image
def image_thumb_filter():
size = 128, 128
for path, dirs, files in os.walk(wd):
for file in files:
if file.endswith(".jpg"):
src = os.path.join(path, file)
#print(src)
dst = os.path.join(os.getcwd(), "Photo_selection")
if not os.path.exists(dst): #Checks 'Photos_mirror' folder exists
otherwise creates
os.makedirs(dst)
new_name = src.replace(wd+'\\', '').replace('\\', '_')
new_dst = os.path.join(dst, new_name + "_thumb")
if not os.path.isfile(new_dst):
if "99\\526" in src:
try:
im = image.open(src)
im.thumbnail(size)
im.save(new_dst, "JPEG")
except IOError:
print ("cannot create thumbnail for", infile)
shutil.copy(src, dst)
old_dst = os.path.join(dst, file)
#Assuming your /dir/dir/... structure is inside of your working
directory (wd)
os.rename(old_dst, new_dst)
else: # it doesn't like this else statement
continue
image_thumb_filter()
You have not defined the object "Image" specifically anywhere in your code. Remember that Python and many other languages are case sensitive. Maybe you meant "image?"

generate gif with images2gif

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')))

How can I use a variable instead of a path to open an image file using PIL in Python?

I'm trying to create a simple script to pull EXIF information out from multiple jpeg files at once, but I'm getting "IOError: cannot identify image file" when trying to use a variable instead of an absolute path. Here's the code that I'm using:
import os
from PIL import Image, ExifTags
source = raw_input("Enter the path to scan")
os.chdir(source)
for root, dirs, files in os.walk(source):
for file_name in files:
img = Image.open(file_name)
exif = { ExifTags.TAGS[k]: vars for k, vars in img._getexif().items() if k in ExifTags.TAGS }
print exif
I have also tried using StringIO per a tip I noticed while Google searching my problem. The code is the same as above except I import StringIO and make the following change in the Image.open code:
img = Image.open(StringIO(file_name))
This did not fix the problem and I get the same error. If I give a path instead of a variable in Image.open, it does work correctly so I know the problem is trying to use a variable. Is there a way to do this that I'm missing?
You need to use this code instead:
img = Image.open(os.path.join(root, file_name))
If you have any non-image files in your directory hierarchy, then you will still have an error when you try to open them, but that is a legitimate error, so you could do something like:
try:
img = Image.open(os.path.join(root, file_name))
except IOError:
print "Error: %s does not appear to be a valid image" % (os.path.join(root, file_name))
else:
exif = ...

Categories

Resources