示例#1
0
文件: Drawing.cs 项目: cvogt/AlbLib
        /// <summary>
        /// Converts bitmap to byte array using external palette.
        /// </summary>
        public static byte[] LoadBitmap(Bitmap bmp, ImagePalette palette)
        {
            byte[] result = new byte[bmp.Width * bmp.Height];
            var    rect   = new Rectangle(Point.Empty, bmp.Size);

            if (bmp.Palette.Entries.SequenceEqual(palette, ColorComparer.Instance))
            {
                BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
                for (int y = 0; y < bmp.Height; y++)
                {
                    Marshal.Copy(data.Scan0 + data.Stride * y, result, y * bmp.Width, bmp.Width);
                }
                bmp.UnlockBits(data);
            }
            else
            {
                BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                for (int y = 0; y < bmp.Height; y++)
                {
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        byte b = Marshal.ReadByte(data.Scan0, y * data.Stride + x * 3);
                        byte g = Marshal.ReadByte(data.Scan0, y * data.Stride + x * 3 + 1);
                        byte r = Marshal.ReadByte(data.Scan0, y * data.Stride + x * 3 + 2);
                        result[y * bmp.Width + x] = (byte)palette.GetNearestColorIndex(Color.FromArgb(r, g, b));
                    }
                }
                bmp.UnlockBits(data);
            }
            return(result);
        }