예제 #1
0
        private void ReadPixel()
        {
            string pathOfBitmapMap = $@"{Application.StartupPath}\{@"Gfx\provinces.bmp"}";

            if (File.Exists(pathOfBitmapMap) == false)
            {
                return;
            }

            int idProvince = GetMaxIdProvince();

            var dictCache = Provinces.ToDictionary(p => $"{p.R}{p.G}{p.B}");

            BitmapMap = new Bitmap(Image.FromFile(pathOfBitmapMap));

            m_mapProvinceDefinitionItem = new ProvinceDefinitionItem[BitmapMap.Width, BitmapMap.Height];

            Rectangle rectangle = new Rectangle(0, 0, BitmapMap.Width, BitmapMap.Height);

            BitmapData bitmapData = BitmapMap.LockBits(rectangle, ImageLockMode.ReadOnly, BitmapMap.PixelFormat);

            int length = bitmapData.Stride * BitmapMap.Height;

            byte[] rawBytes = new byte[length];

            System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, rawBytes, 0, length);

            BitmapMap.UnlockBits(bitmapData);

            var province = new ProvinceDefinitionItem();

            var colorKey = new StringBuilder();

            for (int nXndex = 0; nXndex < BitmapMap.Width; nXndex++)
            {
                for (int nYndex = 0; nYndex < BitmapMap.Height; nYndex++)
                {
                    var pixelColor = Color.FromArgb(rawBytes[nYndex * bitmapData.Stride + nXndex * 4 + 3], rawBytes[nYndex * bitmapData.Stride + nXndex * 4 + 2], rawBytes[nYndex * bitmapData.Stride + nXndex * 4 + 1], rawBytes[nYndex * bitmapData.Stride + nXndex * 4]);

                    if (!(province.R == pixelColor.R && province.G == pixelColor.G && province.B == pixelColor.B))
                    {
                        colorKey.Clear();

                        colorKey.Append(pixelColor.R);
                        colorKey.Append(pixelColor.G);
                        colorKey.Append(pixelColor.B);

                        var colorKeyString = colorKey.ToString();

                        province = dictCache.ContainsKey(colorKeyString) ?
                                   dictCache[colorKeyString] :
                                   new ProvinceDefinitionItem(++idProvince, pixelColor.R, pixelColor.G, pixelColor.B, $"NewProvince_{idProvince}", string.Empty);
                    }

                    province.Pixels.Add(new Pixel(nXndex, nYndex));

                    m_mapProvinceDefinitionItem[nXndex, nYndex] = province;
                }
            }

            BitmapMapOverlay = new Bitmap(BitmapMap);
        }