Mega Code Archive

 
Categories / Delphi / Graphic
 

Convert BMP to Any Format (.NET)

Title: Convert BMP to *Any Format* (.NET) Question: When working in .NET you pretty much have to re-learn the VCL, (FCL) to accomplish every single task there's tons of code for Win32 to convert images to/from formats, here I show you how to convert an Image from BMP to any format (JPG, PNG, GIF, etc) in .NET Answer: the FCL provides methods to do many image manipulation tricks, you just have to know where to find them this function will do the job for you procedure TWinForm3.Bmp2AnyFormat(theBmp:Bitmap; const FileName:string; const ImgFormat:ImageFormat); var fs:FileStream; begin fs:=FileStream.Create(FileName, FileMode.CreateNew); try try theBmp.Save(fs, ImgFormat); except on E:Exception do raise Exception.Create('Error converting image: '+E.Message); end finally fs.Close end end; the Bitmap class comes from System.Drawing.Imaging the FileStream comes from: System.IO so you'll need those in your uses clause now, an example of use: say you have a PictureBox with a .BMP on it in your form, and you wanted to save that as a jpeg I put some code to load a bmp at runtime: procedure TWinForm3.TWinForm3_Load(sender: System.Object; e: System.EventArgs); begin PictureBox1.Image:=Image.FromFile('c:\SomeFile.bmp'); end; then a button to convert the image (to JPEG) using the function: procedure TWinForm3.Button1_Click(sender: System.Object; e: System.EventArgs); begin Bmp2AnyFormat(Bitmap(PictureBox1.Image), 'f:\new.jpg', ImageFormat.Jpeg) end; you can use ImageFormat.Tiff, ImageFormat.Gif, ImageFormat.Png, ImageFormat.Jpeg, etc... that's it, as you can see, is really easy... the hard part is to find which class does what best regards