private Bitmap ExtendCanvasSizeOf8BitBitmap(Bitmap source, int newWidth, int newHeight)
{
if (source.PixelFormat != PixelFormat.Format8bppIndexed)
{
throw new AGSEditorException("This function only works with 8-bit images; use built-in .net routines for higher colour depths");
}
int bytesPerPixel = 1;
Bitmap paddedBmp = new Bitmap(newWidth, newHeight, source.PixelFormat);
Rectangle sourceRect = new Rectangle(0, 0, source.Width, source.Height);
BitmapData sourceData = source.LockBits(sourceRect, ImageLockMode.ReadOnly, source.PixelFormat);
Rectangle destRect = new Rectangle(0, 0, paddedBmp.Width, paddedBmp.Height);
BitmapData bmpData = paddedBmp.LockBits(destRect, ImageLockMode.WriteOnly, paddedBmp.PixelFormat);
int srcMemoryAddress = sourceData.Scan0.ToInt32();
int memoryAddress = bmpData.Scan0.ToInt32();
for (int y = 0; y < newHeight; y++)
{
byte[] line = new byte[bmpData.Stride];
Array.Clear(line, 0, line.Length);
if (y < source.Height)
{
Marshal.Copy(new IntPtr(srcMemoryAddress), line, 0, source.Width * bytesPerPixel);
}
Marshal.Copy(line, 0, new IntPtr(memoryAddress), line.Length);
srcMemoryAddress += sourceData.Stride;
memoryAddress += bmpData.Stride;
}
paddedBmp.UnlockBits(bmpData);
source.UnlockBits(sourceData);
ColorPalette sourcePalette = source.Palette;
ColorPalette destPalette = paddedBmp.Palette;
for (int i = 0; i < sourcePalette.Entries.Length; i++)
{
destPalette.Entries[i] = sourcePalette.Entries[i];
}
// The palette needs to be re-set onto the bitmap to force it
// to update its internal storage of the colours
paddedBmp.Palette = destPalette;
source.Dispose();
return paddedBmp;
}