It's as simple as this:
# convert a .png image file to a .bmp image file using PIL
from PIL import Image
file_in = "test1.png"
img = Image.open(file_in)
file_out = "test1.bmp"
img.save(file_out)
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Strange, my test1.png image file is full color and I have no problems.
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Thanks nezachem!
Looks like my .png image file only has RGB and not RGBA. You could use this modified code:
# convert a .png image file to a .bmp image file using PIL
from PIL import Image
file_in = "test.png"
img = Image.open(file_in)
file_out = "test2.bmp"
print len(img.split()) # test
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save(file_out)
else:
img.save(file_out)
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Thanks nezachem!
Looks like my .png image file only has RGB and not RGBA. You could use this modified code:
# convert a .png image file to a .bmp image file using PIL
from PIL import Image
file_in = "test.png"
img = Image.open(file_in)
file_out = "test2.bmp"
print len(img.split()) # test
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.save(file_out)
else:
img.save(file_out)
Not sure what is going on, but I get these double posts with DaniWeb.
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
Notice that independently from the pythonic solution above, one can use imagemagick on the command line, it's a specialized tool to convert between image formats. Here is a working command once imagemagick is installed
convert temp.png temp.bmp
This command has many options to manipulate size, color, transparency, etc.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
That sounds good but I needed to do everything in Python. Unless this can be run from Python or imported as a module within it?
Actually, it can be used from python. The first way is to use the subprocess module to call imagemagick externally like in subprocess.call("convert temp.png temp.bmp", shell=True), but this is cheating because any program can be called from python this way. Another way is to use one of the imagemagick's python APIs. However, I never tried this myself :)
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691