public Bitmap ToManagedImage( bool makeCopy )
{
Bitmap dstImage = null;
try
{
if ( !makeCopy )
{
dstImage = new Bitmap( width, height, stride, pixelFormat, imageData );
if ( pixelFormat == PixelFormat.Format8bppIndexed )
{
Image.SetGrayscalePalette( dstImage );
}
}
else
{
// create new image of required format
dstImage = ( pixelFormat == PixelFormat.Format8bppIndexed ) ?
AForge.Imaging.Image.CreateGrayscaleImage( width, height ) :
new Bitmap( width, height, pixelFormat );
// lock destination bitmap data
BitmapData dstData = dstImage.LockBits(
new Rectangle( 0, 0, width, height ),
ImageLockMode.ReadWrite, pixelFormat );
int dstStride = dstData.Stride;
int lineSize = Math.Min( stride, dstStride );
unsafe
{
byte* dst = (byte*) dstData.Scan0.ToPointer( );
byte* src = (byte*) imageData.ToPointer( );
if ( stride != dstStride )
{
// copy image
for ( int y = 0; y < height; y++ )
{
AForge.SystemTools.CopyUnmanagedMemory( dst, src, lineSize );
dst += dstStride;
src += stride;
}
}
else
{
AForge.SystemTools.CopyUnmanagedMemory( dst, src, stride * height );
}
}
// unlock destination images
dstImage.UnlockBits( dstData );
}
return dstImage;
}
catch ( Exception )
{
if ( dstImage != null )
{
dstImage.Dispose( );
}
throw new InvalidImagePropertiesException( "The unmanaged image has some invalid properties, which results in failure of converting it to managed image." );
}
}