March 21st, 2005, 10:26 PM
tga to jpg with python
Does python have any modules that can open a tga file, then once open i can save the same file as a jpg file? If there is just point me in the right direction, i will figure out how i want to use it.
March 21st, 2005, 10:49 PM
March 22nd, 2005, 08:41 AM
Yes, you can easily do it with PIL, but it hasn't been updated for Python version 2.4 yet!
March 22nd, 2005, 11:46 AM
thanks guys, that was perfect here is what i did
import os, sys
dirList = os.listdir("c:\\img\\")
counter = 0
end = len(dirList)
while counter < end:
outfile = dirList[counter] + ".jpg"
print "opening %s" % dirList[counter]
Image.open("c:\\img\\%s" % dirList[counter] ).save("c:\\jpg\\%s" % outfile)
print "saving as %s" % outfile
print "cannot convert", dirList[counter]
counter += 1
March 23rd, 2005, 05:05 AM
I apologise, but I just have to rewrite your "C code that runs in Python" into "Python code"
- Iteration over a list implicitly rather than doing it yourself with a counter
from glob import glob
for picture in glob("c:\\img\\*.tga"):
outfile = os.path.splitext(picture) + ".jpg"
print "Converting: ", picture
print " * Conversion failed for this file."
- Three lots of "c:\\img\\" could get annoying to change and looks a bit untidy.
- os.path.splitext will remove the current extension, so you wont end up with "file001.tga.jpg", etc.
- glob will both: get only .tga files, and include the full pathname in the list of files it returns, so removing the need for: "c:\\img\\%s " % filename.
- Adjusted the messages printed. You know it's converting .tga to .jpg, so why print
for each file, when you could have:
Saving as A.jpg
Failed to convert A
(Errors stand out more, and the filename duplication is reduced. Depending on the future of this, you could have it work with optparse so you could choose to see only failed files. (Because those are the only ones you really care to hear about)).
* Conversion Failed
March 23rd, 2005, 07:36 AM
Well, there is no feture of this code. One of my friends asked me if i knew of any programs that could convert tga files to jpgs without having to hand open all of them and then resave them. There where also bmp files in the mix also, so i just have it open any file type, i just told him to make sure there where no other files types in there, besides images. I didn't know about the splittext, that would have been nice, and thanks for the pointer with the glob, I didn't not know about that.
March 23rd, 2005, 09:11 AM
Don't forget the beginners! Newbees like me can learn a lot from both coding styles. Great thread, thank you very much!
BTW, you can replace the \\ with /
March 23rd, 2005, 05:30 PM