public static UnmanagedImage Create( int width, int height, PixelFormat pixelFormat )
{
int bytesPerPixel = 0 ;
// calculate bytes per pixel
switch ( pixelFormat )
{
case PixelFormat.Format8bppIndexed:
bytesPerPixel = 1;
break;
case PixelFormat.Format16bppGrayScale:
bytesPerPixel = 2;
break;
case PixelFormat.Format24bppRgb:
bytesPerPixel = 3;
break;
case PixelFormat.Format32bppRgb:
case PixelFormat.Format32bppArgb:
case PixelFormat.Format32bppPArgb:
bytesPerPixel = 4;
break;
case PixelFormat.Format48bppRgb:
bytesPerPixel = 6;
break;
case PixelFormat.Format64bppArgb:
case PixelFormat.Format64bppPArgb:
bytesPerPixel = 8;
break;
default:
throw new UnsupportedImageFormatException( "Can not create image with specified pixel format." );
}
// check image size
if ( ( width <= 0 ) || ( height <= 0 ) )
{
throw new InvalidImagePropertiesException( "Invalid image size specified." );
}
// calculate stride
int stride = width * bytesPerPixel;
if ( stride % 4 != 0 )
{
stride += ( 4 - ( stride % 4 ) );
}
// allocate memory for the image
IntPtr imageData = System.Runtime.InteropServices.Marshal.AllocHGlobal( stride * height );
AForge.SystemTools.SetUnmanagedMemory( imageData, 0, stride * height );
UnmanagedImage image = new UnmanagedImage( imageData, width, height, stride, pixelFormat );
image.mustBeDisposed = true;
return image;
}