private void WriteIndexedImage(Stream output, BitmapFrame frame, BitmapPalette[] palettes) { byte[] buff = new byte[4]; foreach (Color color in palettes.SelectMany(p => p.Colors)) { buff[0] = color.B; buff[1] = color.G; buff[2] = color.R; buff[3] = color.A; output.Write(buff, 0, buff.Length); } Int32Rect rect; using (SafeHGlobalHandle buffer = frame.GetPixels(out rect)) { using (UnmanagedMemoryStream ums = new UnmanagedMemoryStream(buffer, buffer.Length, buffer.Length, FileAccess.Read)) ums.CopyTo(output, Math.Min(32 * 1024, buffer.Length)); } }