Introduction
FreeImage is an extremely useful Open Source project for reading, manipulating and converting a large amount of graphical formats. However at present the library exists as Win32 Dynamic Link Library. As my latest fascination is C#, I decided to create a simple Interop wrapper for it.
Using the code
The code is very straightforward to use, which is a reflection on the FreeImage implementation itself. For my needs I wanted to be able to take a picture file in Portable Bitmap (PBM) format and convert it to a standard Bitmap (BMP). For this I needed 3 methods exposed via the FreeImage DLL, FreeImage_Load
, FreeImage_Save
and FreeImage_Unload
, the signature for which are:
DLL_API FIBITMAP *DLL_CALLCONV FreeImage_Load(FREE_IMAGE_FORMAT fif,
const char *filename, int flags FI_DEFAULT(0));
DLL_API BOOL DLL_CALLCONV FreeImage_Save(FREE_IMAGE_FORMAT fif,
FIBITMAP *dib, const char *filename, int flags FI_DEFAULT(0));
DLL_API void DLL_CALLCONV FreeImage_Unload(FIBITMAP* dib);
Now the C# Interop signatures for these are:
public class FreeImage
{
[DllImport("FreeImage.dll")]
public static extern int FreeImage_Load(FIF format,
string filename, int flags);
[DllImport("FreeImage.dll")]
public static extern void FreeImage_Unload(int handle);
[DllImport("FreeImage.dll")]
public static extern bool FreeImage_Save(FIF format,
int handle, string filename, int flags);
}
As an example, to convert a graphical image from PBM to BMP, all you need to do is the following (note the enum
FIF
is not documented here, but can be found in the source code).
namespace Test
{
class MainClass
{
public static void Main(string[] args)
{
int handle = FreeImageAPI.FreeImage.FreeImage_Load(
FreeImageAPI.FIF.FIF_PBM,
@"c:\image.pbm",
0);
FreeImageAPI.FreeImage.FreeImage_Save(
FreeImageAPI.FIF.FIF_BMP,
handle,
@"c:\image.bmp",
0);
FreeImageAPI.FreeImage.FreeImage_Unload(handle);
}
}
}