3

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"

anon01
  • 10,618
  • 8
  • 35
  • 58
David Han
  • 47
  • 3
  • 8
  • Does this answer your question? [Getting "cannot write mode P as JPEG" while operating on JPG image](https://stackoverflow.com/questions/21669657/getting-cannot-write-mode-p-as-jpeg-while-operating-on-jpg-image) – Kaia Aug 27 '20 at 00:15
  • https://stackoverflow.com/a/21669827/1275942 This looks like a similar error; I'm guessing the PNGs are in a weird mode (for instance, PNGs can have an alpha channel while JPGs don't; I don't know the particulars of the "P" mode, but I'd guess it's that or something similar – Kaia Aug 27 '20 at 00:17
  • 1
    that sounds about right, will look into the link more, thanks – David Han Aug 27 '20 at 00:22

2 Answers2

0

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))
David Han
  • 47
  • 3
  • 8
  • In your code, you try to change .jpg file as your if statement should return true. So you, should have put **if not file.endswith(".jpg")** – Nijat Mursali Mar 11 '22 at 18:21
0

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.

Nijat Mursali
  • 930
  • 1
  • 8
  • 20