engineer_me
engineer_me

Reputation: 27

how to convert .bmp images to .png in python

how to convert .bmp images to .png

this is a part of my code, but it doesn’t convert images to png

get_cropped_image(impath).save(outpath,'png')

The code is running, but the images don’t change.

Upvotes: 1

Views: 11768

Answers (2)

Can H. Tartanoglu
Can H. Tartanoglu

Reputation: 378

First install pillow:

pip install pillow

Then run this script on the folder with the .bmp files:

from PIL import Image
import glob
import os

from pathlib import Path

current_dir = Path('.').resolve()

out_dir = current_dir / "converted"
os.mkdir(out_dir)
cnt = 0

for img in glob.glob(str(current_dir / "*.bmp")):
    filename = Path(img).stem
    Image.open(img).save(str(out_dir / f'{filename}.png'))

Upvotes: 0

Zabir Al Nazi Nabil
Zabir Al Nazi Nabil

Reputation: 11218

You can simply use Pillow library. Use glob to read the .bmp images from a folder, Pillow to resize and save as .png.

from PIL import Image
import glob
import os

out_dir = ''
cnt = 0
for img in glob.glob('path/to/images/*.bmp'):
    Image.open(img).resize((300,300)).save(os.path.join(out_dir, str(cnt) + '.png'))
    cnt += 1

ref: https://pillow.readthedocs.io/en/3.1.x/reference/Image.html

Upvotes: 6

Related Questions