public override object Decode( Stream input, Stream output, params object[] args )
{
ImageData data = new ImageData();
Bitmap CurrentBitmap = null;
int bytesPerPixel;
bool gray = false; // gray image is used by terrain's heightmap
try
{
CurrentBitmap = new Bitmap( input );
if ( ( CurrentBitmap.Flags & 64 ) != 0 ) // if grayscale
{
gray = true;
}
switch ( CurrentBitmap.PixelFormat )
{
case SDI.PixelFormat.Format24bppRgb:
bytesPerPixel = 3;
break;
case SDI.PixelFormat.Format32bppRgb:
case SDI.PixelFormat.Format32bppArgb:
bytesPerPixel = 4;
break;
default:
throw new ArgumentException( "Unsupported Pixel Format " + CurrentBitmap.PixelFormat );
}
SDI.BitmapData Data = CurrentBitmap.LockBits( new System.Drawing.Rectangle( 0, 0, CurrentBitmap.Width, CurrentBitmap.Height ), SDI.ImageLockMode.ReadOnly, CurrentBitmap.PixelFormat );
// populate the image data
data.width = Data.Width;
data.height = Data.Height;
data.depth = 1;
data.numMipMaps = 0;
if ( gray )
{
data.format = Axiom.Media.PixelFormat.L8;
data.size = data.width * data.height;
}
else
{
data.format = Axiom.Media.PixelFormat.A8B8G8R8;
data.size = data.width * data.height * 4;
}
// get the decoded data
byte[] buffer = new byte[ data.size ];
// copy the data into the byte array
unsafe
{
int qw = 0;
byte* imgPtr = (byte*)( Data.Scan0 );
if ( gray == false )
{
for ( int i = 0; i < Data.Height; i++ )
{
for ( int j = 0; j < Data.Width; j++ )
{
buffer[ qw++ ] = *( imgPtr + 2 );
buffer[ qw++ ] = *( imgPtr + 1 );
buffer[ qw++ ] = *( imgPtr + 0 );
if ( bytesPerPixel == 3 )
buffer[ qw++ ] = 255;
else
buffer[ qw++ ] = *( imgPtr + 3 ); // alpha
imgPtr += bytesPerPixel;
}
imgPtr += Data.Stride - Data.Width * bytesPerPixel;
}
}
else
{
for ( int i = 0; i < Data.Height; i++ )
{
for ( int j = 0; j < Data.Width; j++ )
{
buffer[ qw++ ] = *( imgPtr );
imgPtr += bytesPerPixel;
}
imgPtr += Data.Stride - Data.Width * bytesPerPixel;
}
}
}
// write the decoded data to the output stream
output.Write( buffer, 0, buffer.Length );
CurrentBitmap.UnlockBits( Data );
}
catch ( Exception e )
{
throw new ArgumentException( "Texture loading error.", e );
}
return data;
}
}