protected override System.Drawing.Size CalculateNewImageSize( UnmanagedImage sourceData )
{
// get source image size
int width = sourceData.Width;
int height = sourceData.Height;
int offset = sourceData.Stride -
( ( sourceData.PixelFormat == PixelFormat.Format8bppIndexed ) ? width : width * 3 );
// color to remove
byte r = colorToRemove.R;
byte g = colorToRemove.G;
byte b = colorToRemove.B;
minX = width;
minY = height;
int maxX = 0;
int maxY = 0;
// find rectangle which contains something except color to remove
unsafe
{
byte* src = (byte*) sourceData.ImageData.ToPointer( );
if ( sourceData.PixelFormat == PixelFormat.Format8bppIndexed )
{
// grayscale
for ( int y = 0; y < height; y++ )
{
for ( int x = 0; x < width; x++, src++ )
{
if ( *src != g )
{
if ( x < minX )
minX = x;
if ( x > maxX )
maxX = x;
if ( y < minY )
minY = y;
if ( y > maxY )
maxY = y;
}
}
src += offset;
}
}
else
{
// RGB
for ( int y = 0; y < height; y++ )
{
for ( int x = 0; x < width; x++, src += 3 )
{
if (
( src[RGB.R] != r ) ||
( src[RGB.G] != g ) ||
( src[RGB.B] != b ) )
{
if ( x < minX )
minX = x;
if ( x > maxX )
maxX = x;
if ( y < minY )
minY = y;
if ( y > maxY )
maxY = y;
}
}
src += offset;
}
}
}
// check
if ( ( minX == width ) && ( minY == height ) && ( maxX == 0 ) && ( maxY == 0 ) )
{
minX = minY = 0;
}
return new Size( maxX - minX + 1, maxY - minY + 1 );
}