This is by far not a definitive answer, but hopefully point you in some directions.
Depending on what OS you are using, you might be able to find a utility that will do what you are asking. I searched for 'bmp2jpg' on Google and it came up with quite a few programs that convert BMPs to JPGs. The main one is a demo of a $99.00 program, but it looks as if it serves your exact purpose of a CGI program on Windows.
If you are using something like Linux, I haven't found anything yet, but you could probably script something like Gimp to convert a BMP to JPG by command line only, and then call that from a CGI program.