public void FillRectangle(System.Drawing.SolidBrush brush, System.Drawing.Rectangle rectangle)
 {
     _renderTarget2D.FillRectangle(
         _rectangleConverter.Convert(rectangle),
         _solidColorBrushConverter.Convert(brush)
         );
 }
        private void AddTxT(object sender, RoutedEventArgs e)
        {
            Color  color            = Color.LightSkyBlue;
            Bitmap TempsourceBitmap = sheetCI;
            Font   font             = new Font("Times New Roman", 12.0f);
            int    Width            = CIimg.Width;
            int    Height           = CIimg.Height;
            float  dpiX             = CIimg.HorizontalResolution;
            float  dpiY             = CIimg.VerticalResolution;

            Bitmap Bitmaptemp = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            BitmapResult = Bitmaptemp;
            BitmapResult.SetResolution(dpiX, dpiY);

            Graphics Grp = Graphics.FromImage(BitmapResult);

            System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Height);

            Grp.DrawImage(CIimg, 0, 0, Rec, GraphicsUnit.Pixel);
            System.Drawing.Brush brush = System.Drawing.Brushes.Black;
            Grp.DrawString(InputTxT.Text, font, brush, 0, 0);
            Grp.ResetTransform();
            Grp.Dispose();
            GC.Collect();
        }
        private void GetCutImage()
        {
            int tempLeft   = (int)Canvas.GetLeft(rectangle);
            int tempTop    = (int)Canvas.GetTop(rectangle);
            int tempWidth  = (int)rectangle.Width;
            int tempHeight = (int)rectangle.Height;

            System.Drawing.Image currentImage;
            System.Drawing.Image processImage;
            //currentImage = System.Drawing.Image.FromFile(@"D:\公司项目\测试的代码\CutImageTest\CutImageTest\10.jpg");
            currentImage = ImageWork.ImageSourceToBitmap(sourceImg.Source);//获取原图片
            System.Drawing.Rectangle SelectedRect  = new Rectangle(tempLeft, tempTop, tempWidth, tempHeight);
            System.Drawing.Rectangle _selectedRect = MapSelectedRegion(sourceImg, SelectedRect, currentImage);
            //System.Drawing.Rectangle _selectedRect = new System.Drawing.Rectangle(tempLeft, tempTop, tempWidth, tempHeight);
            processImage = ImageWork.ClipImage(currentImage,
                                               _selectedRect,
                                               (int)targetImg.Width,
                                               (int)targetImg.Height,
                                               System.Drawing.Color.Black
                                               );
            Bitmap      bmp         = new Bitmap(processImage); // get bitmap
            BitmapImage bmpResource = ImageWork.BitmapToBitmapImage(bmp);

            targetImg.Source = bmpResource;
        }
        public static BitmapSource CreateBitmapSourceFromGdiBitmap(Bitmap bitmap)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException("bitmap");
            }

            var rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);

            var bitmapData = bitmap.LockBits(
                rect,
                ImageLockMode.ReadWrite,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            try
            {
                var size = (rect.Width * rect.Height) * 4;

                return(BitmapSource.Create(
                           bitmap.Width,
                           bitmap.Height,
                           bitmap.HorizontalResolution,
                           bitmap.VerticalResolution,
                           PixelFormats.Bgra32,
                           null,
                           bitmapData.Scan0,
                           size,
                           bitmapData.Stride));
            }
            finally
            {
                bitmap.UnlockBits(bitmapData);
            }
        }
Exemple #5
0
        private bool Ch4()
        {
            var res = false;
            var sw  = new Stopwatch();
            var r   = Imports.NativeMethods.GetAbsoluteClientRect(BdoP.MainWindowHandle);
            var X   = r.X;
            var Y   = r.Y;
            var CAX = X + r.Width / 2;
            var CAY = Y + r.Height / 2;

            sw.Start();
            while (!res && sw.ElapsedTicks < TimeSpan.FromMilliseconds(time).Ticks)
            {
                var b = new Sbmp(_sc);

                var Filtr = new System.Drawing.Rectangle(CAX - 409, CAY - 216, 38, 10);
                if (_mfiltr.Compare(b, Filtr))
                {
                    res = true;
                    b.Dispose();
                    break;
                }
                b.Dispose();
                System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
            }
            sw.Stop();
            return(res);
        }
 private static Point ScreenCenter()
 {
     System.Drawing.Rectangle screenBounds = Screen.PrimaryScreen.Bounds;
     return(new Point(
                (screenBounds.Left + screenBounds.Right) / 2,
                (screenBounds.Top + screenBounds.Bottom) / 2));
 }
Exemple #7
0
        // To avoid filtering artifacts when scaling or rotating fonts that do not use premultiplied alpha,
        // make sure the one pixel border around each glyph contains the same RGB values as the edge of the
        // glyph itself, but with zero alpha. This processing is an elaborate no-op when using premultiplied
        // alpha, because the premultiply conversion will change the RGB of all such zero alpha pixels to black.
        public static void PadBorderPixels(Bitmap bitmap, System.Drawing.Rectangle region)
        {
            using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite))
            {
                // Pad the top and bottom.
                for (int x = region.Left; x < region.Right; x++)
                {
                    CopyBorderPixel(bitmapData, x, region.Top, x, region.Top - 1);
                    CopyBorderPixel(bitmapData, x, region.Bottom - 1, x, region.Bottom);
                }

                // Pad the left and right.
                for (int y = region.Top; y < region.Bottom; y++)
                {
                    CopyBorderPixel(bitmapData, region.Left, y, region.Left - 1, y);
                    CopyBorderPixel(bitmapData, region.Right - 1, y, region.Right, y);
                }

                // Pad the four corners.
                CopyBorderPixel(bitmapData, region.Left, region.Top, region.Left - 1, region.Top - 1);
                CopyBorderPixel(bitmapData, region.Right - 1, region.Top, region.Right, region.Top - 1);
                CopyBorderPixel(bitmapData, region.Left, region.Bottom - 1, region.Left - 1, region.Bottom);
                CopyBorderPixel(bitmapData, region.Right - 1, region.Bottom - 1, region.Right, region.Bottom);
            }
        }
 public void DrawImage(System.Drawing.Bitmap bitmap, System.Drawing.Rectangle rectangle)
 {
     _renderTarget2D.DrawBitmap(
         bitmap: _bitmapHelper.LoadFromFile(_renderTarget2D, bitmap),
         destinationRectangle: _rectangleConverter.Convert(rectangle),
         opacity: 1.0f,
         interpolationMode: BitmapInterpolationMode.Linear);
 }
        public static void TestText()
        {
            System.Drawing.Rectangle screenBounds = Screen.PrimaryScreen.Bounds;
            //RecognizeText(screenBounds.Width / 4, screenBounds.Height / 4, new Size(200, 200));
            Point result;

            RecognizeText(gazeX, gazeY, new Size(300, 300), "testing", out result);
        }
 public void DrawRectangle(System.Drawing.Pen pen, System.Drawing.Rectangle rectangle)
 {
     _renderTarget2D.DrawRectangle(
         _rectangleConverter.Convert(rectangle),
         new SolidColorBrush(_renderTarget2D,
                             new Color4(red: pen.Color.R, blue: pen.Color.B, green: pen.Color.G, alpha: pen.Color.A)
                             )
         );
 }
 public void DrawRectangle(System.Drawing.Pen pen, System.Drawing.Rectangle rectangle)
 {
     _renderTarget2D.DrawRectangle(
         _rectangleConverter.Convert(rectangle),
         new SolidColorBrush(_renderTarget2D,
                             new SharpDX.Mathematics.Interop.RawColor4(r: pen.Color.R, b: pen.Color.B, g: pen.Color.G, a: pen.Color.A)
                             )
         );
 }
Exemple #12
0
        private Bitmap GetScreen()
        {
            System.Drawing.Rectangle rc = System.Windows.Forms.SystemInformation.VirtualScreen;
            ScreenShot = new Bitmap(rc.Width, rc.Height);

            using (Graphics g = Graphics.FromImage(ScreenShot))
            {
                g.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy);
            }
            ScreenShot.Save("D:\\VS2017Project\\SnipOCR\\SnipOCR\\resources\\123.png");

            return(ScreenShot);
        }
Exemple #13
0
        private void btn2_Click(object sender, RoutedEventArgs e)
        {
            IntPtr findwindow = FindWindow(null, AppName);

            if (findwindow != IntPtr.Zero)
            {
                //플레이어를 찾았을 경우
                lblState.Content = "찾았습니다.";

                //찾은 플레이어를 바탕으로 Graphics 정보를 가져옵니다.
                Graphics Graphicsdata = Graphics.FromHwnd(findwindow);

                //찾은 플레이어 창 크기 및 위치를 가져옵니다.
                System.Drawing.Rectangle rect = System.Drawing.Rectangle.Round(Graphicsdata.VisibleClipBounds);

                //플레이어 창 크기 만큼의 비트맵을 선언해줍니다.
                Bitmap bmp = new Bitmap(rect.Width, rect.Height);

                //비트맵을 바탕으로 그래픽스 함수로 선언해줍니다.
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    //찾은 플레이어의 크기만큼 화면을 캡쳐합니다.
                    IntPtr hdc = g.GetHdc();
                    PrintWindow(findwindow, hdc, 0x2);
                    g.ReleaseHdc(hdc);
                }

                // pictureBox1 이미지를 표시해줍니다.

                using (MemoryStream memory = new MemoryStream())
                {
                    bmp.Save(memory, ImageFormat.Bmp);
                    memory.Position = 0; BitmapImage bitmapimage = new BitmapImage();
                    bitmapimage.BeginInit();
                    bitmapimage.StreamSource = memory;
                    bitmapimage.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmapimage.EndInit();
                    imgPrint.Source = bitmapimage;
                    bmp.Save("D:\\myBitmap.bmp");
                }
            }
            else
            {
                //플레이어를 못찾을경우
                lblState.Content = "못찾았어요";
            }
        }
            public SharpDX.Direct2D1.Bitmap LoadFromFile(RenderTarget renderTarget, System.Drawing.Bitmap bitmap)
            {
                SharpDX.Direct2D1.Bitmap match;

                if (_cache.TryGetValue(bitmap, out match))
                {
                    return(match);
                }

                var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                var size             = new Size2(bitmap.Width, bitmap.Height);

                // Transform pixels from BGRA to RGBA
                int stride = bitmap.Width * sizeof(int);

                using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                {
                    // Lock System.Drawing.Bitmap
                    var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                    // Convert all pixels
                    for (int y = 0; y < bitmap.Height; y++)
                    {
                        int offset = bitmapData.Stride * y;
                        for (int x = 0; x < bitmap.Width; x++)
                        {
                            // Not optimized
                            byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                            int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                            tempStream.Write(rgba);
                        }
                    }
                    bitmap.UnlockBits(bitmapData);
                    tempStream.Position = 0;

                    match = new SharpDX.Direct2D1.Bitmap(renderTarget, size, tempStream, stride, bitmapProperties);

                    _cache.TryAdd(bitmap, match);
                }
                return(match);
            }
Exemple #15
0
 public static void CopyRegionIntoImage(Image <Rgba32> srcBitmap, System.Drawing.Rectangle srcRegion,
                                        ref Image <Rgba32> destBitmap,
                                        System.Drawing.Rectangle destRegion)
 {
     using (var newImage = srcBitmap.Clone(x =>
     {
         x.Crop(new SixLabors.Primitives.Rectangle(srcRegion.X, srcRegion.Y, srcRegion.Width,
                                                   srcRegion.Height));
     }))
     {
         var nwImage = newImage;
         destBitmap.Mutate(context =>
         {
             context.DrawImage(nwImage, new Point(destRegion.Location.X, destRegion.Location.Y),
                               PixelColorBlendingMode.Normal, 1f);
         });
     }
 }
Exemple #16
0
        // Copies a rectangular area from one bitmap to another.
        public static void CopyRect(Bitmap source, System.Drawing.Rectangle sourceRegion, Bitmap output, System.Drawing.Rectangle outputRegion)
        {
            if (sourceRegion.Width != outputRegion.Width ||
                sourceRegion.Height != outputRegion.Height)
            {
                throw new ArgumentException();
            }

            using (var sourceData = new PixelAccessor(source, ImageLockMode.ReadOnly, sourceRegion))
                using (var outputData = new PixelAccessor(output, ImageLockMode.WriteOnly, outputRegion))
                {
                    for (int y = 0; y < sourceRegion.Height; y++)
                    {
                        for (int x = 0; x < sourceRegion.Width; x++)
                        {
                            outputData[x, y] = sourceData[x, y];
                        }
                    }
                }
        }
 public static void DebugCharacterRecognition()
 {
     mainForm.Invoke((Action)(() =>
     {
         if (ocrDebugForm != null)
         {
             // Hide and show to bring it to top
             bool wasVisible = ocrDebugForm.Visible;
             ocrDebugForm.Hide();
             ocrDebugForm.Show();
             if (!wasVisible)
             {
                 // Push to the corner only if shown for the first time (allow them to move it afterwards)
                 System.Drawing.Rectangle screenBounds = Screen.PrimaryScreen.Bounds;
                 ocrDebugForm.Left = screenBounds.Right - ocrDebugForm.Width;
                 ocrDebugForm.Top = screenBounds.Top;
             }
         }
     }));
 }
        public static Bitmap CreateFillPatternImage(FillPattern fillPattern)
        {
            var    width          = 30;
            var    height         = 30;
            Bitmap fillPatternImg = new Bitmap((int)width, (int)height);

            try
            {
                using (var g = Graphics.FromImage(fillPatternImg))
                {
                    var rect = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);
                    g.FillRectangle(System.Drawing.Brushes.Transparent, rect);
                    DrawFillPattern(g, fillPattern);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(fillPatternImg);
        }
Exemple #19
0
        private void btnPrintWindow_Click(object sender, RoutedEventArgs e)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            for (int i = 0; i < 100; i++)
            {
                IntPtr findwindow = FindWindow(null, AppName);
                if (findwindow != IntPtr.Zero)
                {
                    Graphics Graphicsdata         = Graphics.FromHwnd(findwindow);
                    System.Drawing.Rectangle rect = System.Drawing.Rectangle.Round(Graphicsdata.VisibleClipBounds);

                    using (Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb))
                    {
                        using (Graphics g = Graphics.FromImage(bmp))
                        {
                            IntPtr hdc = g.GetHdc();
                            PrintWindow(findwindow, hdc, 0x2);
                            g.ReleaseHdc(hdc);
                        }
                        printImg(bmp, imgSpeed);
                        //bmp.Save("D:\\PrintWindow.png");
                    }
                }
                else
                {
                    MessageBox.Show("no");
                }
            }


            sw.Stop();

            lblSpeed.Content = "PrintWindow\t\t" + sw.ElapsedMilliseconds.ToString();
        }
Exemple #20
0
        private static Bitmap DrawLevel(int[,] quadLevel)
        {
            var tiles = System.Drawing.Image.FromFile(@"C:\Users\admin\Source\Repos\pdsharp\SharpDungeon\Assets\tiles0.png") as Bitmap;

            var tileImages = new Bitmap[64];
            var index      = 0;

            for (var j = 0; j < 4; j++)
            {
                for (var i = 0; i < 16; i++)
                {
                    tileImages[index] = new Bitmap(16, 16);
                    using (var g = Graphics.FromImage(tileImages[index]))
                    {
                        var destRect = new System.Drawing.Rectangle(0, 0, 16, 16);
                        var srcRect  = new System.Drawing.Rectangle(i * 16, j * 16, 16, 16);
                        g.DrawImage(tiles, destRect, srcRect, GraphicsUnit.Pixel);
                    }
                    index++;
                }
            }

            var levelBitmap = new Bitmap(512, 512);
            var g2          = Graphics.FromImage(levelBitmap);

            for (int i = 0; i < 32; i++)
            {
                for (int j = 0; j < 32; j++)
                {
                    var b = (byte)quadLevel[i, j];
                    g2.DrawImage(tileImages[b], new Rectangle(i * 16, j * 16, 16, 16), new Rectangle(0, 0, 16, 16),
                                 GraphicsUnit.Pixel);
                }
            }
            return(levelBitmap);
        }
        public static bool RecognizeText(int x, int y, Size regionSize, string searchWord, out Point hitPoint)
        {
            bool result = false;

            hitPoint = new Point(0, 0);
            if (ocrEngine == null)
            {
                return(result);
            }

            Point  origin = new Point(x - regionSize.Width / 2, y - regionSize.Height / 2);
            Bitmap b      = new Bitmap(regionSize.Width, regionSize.Height);

            using (Graphics g = Graphics.FromImage(b))
            {
                g.CopyFromScreen(origin.X, origin.Y, 0, 0, regionSize, CopyPixelOperation.SourceCopy);
            }
            //b = new Bitmap(Image.FromFile("Capture.JPG"));

            Point      imageLocalPoint;
            IOcrResult ocrResult = ocrEngine.Recognize(b);

            // Try finding variations of the search word for all common mis-recognitions
            List <string> variations = new List <string>();

            variations.Add(searchWord);
            if (searchWord.ToLower().Contains('l'))
            {
                variations.Add(searchWord.ToLower().Replace('l', 'I'));
            }
            if (searchWord.ToUpper().Contains('O'))
            {
                variations.Add(searchWord.ToUpper().Replace('O', '0'));
            }

            foreach (string v in variations)
            {
                if (ocrResult.FindWord(v, out imageLocalPoint))
                {
                    hitPoint = new Point(origin.X + imageLocalPoint.X, origin.Y + imageLocalPoint.Y);
                    result   = true;
                    break;
                }
            }


            string text = "Search word: '" + searchWord + "'\r\n";

            text += ocrResult.GetDebugText();

            ocrResult.Dispose();

            mainForm.Invoke((Action)(() =>
            {
                if (!result)
                {
                    if (ocrResponseForm == null)
                    {
                        ocrResponseForm = new OcrResponseForm();
                        ocrResponseForm.FormClosed += OnOcrResponseFormClosed;
                        ocrResponseForm.FormClosing += OnOcrResponseFormClosing;
                    }

                    string responseText = searchWord + "?";
                    ocrResponseForm.Show(responseText);

                    System.Drawing.Rectangle screenBounds = Screen.PrimaryScreen.Bounds;
                    ocrResponseForm.Left = screenBounds.Right - ocrResponseForm.Width;
                    ocrResponseForm.Top = screenBounds.Top;
                }
                {
                    if (ocrDebugForm == null)
                    {
                        ocrDebugForm = new OcrDebugForm();
                        ocrDebugForm.FormClosed += OnOcrFormClosed;
                        ocrDebugForm.FormClosing += OnOcrFormClosing;
                    }
                    if (ocrDebugForm.ocrPicture.Image != null)
                    {
                        ocrDebugForm.ocrPicture.Image.Dispose();
                    }
                    ocrDebugForm.ocrPicture.Image = b;
                    ocrDebugForm.ocrText.Text = text;
                }
            }));

            return(result);
        }
        public static Bitmap ToWhiteBorder(System.Drawing.Bitmap bmpOriginal, System.Drawing.KnownColor knownColor)
        {
            System.Drawing.Color subColor = GetCompatibleColor(knownColor);

            Bitmap untouchedImage = CreateNonIndexedImage(bmpOriginal);
            Bitmap bmp            = CreateNonIndexedImage(bmpOriginal);

            System.Drawing.Size size = bmp.Size;

            isBlack              = new bool[bmp.Width, bmp.Height];
            wasChecked           = new bool[bmp.Width, bmp.Height];
            alreadyAdded         = new bool[bmp.Width, bmp.Height];
            bool[,] isContiguous = new bool[bmp.Width, bmp.Height];
            pixels = new Color[bmp.Width, bmp.Height];
            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 0; y < bmp.Height; y++)
                {
                    isBlack[x, y]      = false;
                    wasChecked[x, y]   = false;
                    alreadyAdded[x, y] = false;
                    pixels[x, y]       = bmp.GetPixel(x, y);
                }
            }
            bmpSize = bmp.Size;



            List <Point> continguousEdges = new List <Point>();
            Point        startPoint       = new Point(5, 5);

            continguousEdges.Add(startPoint);
            Point topRight = new Point(bmp.Width - 5, 5);

            continguousEdges.Add(topRight);
            Point bottomRight = new Point(bmp.Width - 5, bmp.Height - 5);

            continguousEdges.Add(bottomRight);

            bool pointAdded = true;

            while (continguousEdges.Count > 0)
            {
                pointAdded = false;

                if (continguousEdges.Count > 0)
                {
                    Point point = continguousEdges[0];

                    // Check in each direction

                    //left
                    if (!AlreadyAdded(point.X - 1, point.Y, ref bmp) && IsBlack(point.X - 1, point.Y, ref bmp))
                    {
                        alreadyAdded[point.X - 1, point.Y] = true;
                        continguousEdges.Add(new Point(point.X - 1, point.Y));
                        pointAdded = true;
                    }

                    //right
                    if (!AlreadyAdded(point.X + 1, point.Y, ref bmp) && IsBlack(point.X + 1, point.Y, ref bmp))
                    {
                        alreadyAdded[point.X + 1, point.Y] = true;
                        continguousEdges.Add(new Point(point.X + 1, point.Y));
                        pointAdded = true;
                    }

                    //Up
                    if (!AlreadyAdded(point.X, point.Y - 1, ref bmp) && IsBlack(point.X, point.Y - 1, ref bmp))
                    {
                        alreadyAdded[point.X, point.Y - 1] = true;
                        continguousEdges.Add(new Point(point.X, point.Y - 1));
                        pointAdded = true;
                    }

                    //Down
                    if (!AlreadyAdded(point.X, point.Y + 1, ref bmp) && IsBlack(point.X, point.Y + 1, ref bmp))
                    {
                        alreadyAdded[point.X, point.Y + 1] = true;
                        continguousEdges.Add(new Point(point.X, point.Y + 1));
                        pointAdded = true;
                    }

                    foreach (var pt in continguousEdges)
                    {
                        if ((pt.X == point.X) && (pt.Y == point.Y))
                        {
                            continguousEdges.Remove(pt);
                            break;
                        }
                    }
                }
            }

            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 0; y < bmp.Height; y++)
                {
                    if (alreadyAdded[x, y])
                    {
                        isBlack[x, y] = true;
                    }
                }
            }


            int xMiddle = bmp.Width / 2 + 50;
            // Find top of bottom border (we want to invert the bottom)
            int innerBottomBorder = bmp.Height;

            for (int y = bmp.Height - 1; y > bmp.Height / 2; y--)
            {
                if (isBlack[xMiddle, y])
                {
                    innerBottomBorder = y;
                }
                else
                {
                    //break;
                }
            }
            int innerTopBorder = 0;

            for (int y = 1; y < bmp.Height / 2; y++)
            {
                if (isBlack[xMiddle, y])
                {
                    innerTopBorder = y;
                }
                else
                {
                    //break;
                }
            }

            int innerLeft  = 0;
            int innerRight = bmp.Width;

            // Find the inner-left and inner-right border
            for (int x = 2; x < bmp.Width / 2; x++)
            {
                if (isBlack[x, 25])
                {
                    innerLeft = x;
                }
                else
                {
                    //break;
                }
            }

            // Find the inner-left and inner-right border
            for (int x = bmp.Width - 1; x > bmp.Width / 2; x--)
            {
                if (isBlack[x, 25])
                {
                    innerRight = x;
                }
                else
                {
                    //break;
                }
            }



            System.Drawing.Color drawingColor = subColor;

            System.Drawing.Bitmap whitedOut = bmp;

            // Detect system cards and force a 15-pixel border
            if ((innerBottomBorder < bmp.Height - 1) && (innerTopBorder > 0) && (innerLeft > 0) && (innerRight < bmp.Width))
            {
                int defaultBorder = 15;
                int maxBorder     = 25;
                if ((innerBottomBorder < (bmp.Height - maxBorder)) ||
                    (innerTopBorder > maxBorder) ||
                    (innerLeft > maxBorder) ||
                    (innerRight < bmp.Width - maxBorder))
                {
                    // System card detected!  Add 4 borders of 15 pixels each!
                    innerBottomBorder = bmp.Height - defaultBorder;
                    innerTopBorder    = defaultBorder;
                    innerLeft         = defaultBorder;
                    innerRight        = bmp.Width - defaultBorder;
                }
            }

            /*
             * // Invert the bottom-border and then sub-out all of the other pixels
             * for (int x = 0; x < whitedOut.Width; x++)
             * {
             *  for (int y = 0; y < whitedOut.Height; y++)
             *  {
             *      if (y >= innerBottomBorder)
             *      {
             *          Color oldPixel = whitedOut.GetPixel(x, y);
             *          whitedOut.SetPixel(x, y, Color.FromArgb(255 - oldPixel.R, 255 - oldPixel.G, 255 - oldPixel.B));
             *      }
             *
             *
             *      if ((x <= innerLeft) || (x >= innerRight) || (y <= innerTopBorder) || (y >= innerBottomBorder))
             *      {
             *          if (isBlack[x, y])
             *          {
             *              whitedOut.SetPixel(x, y, drawingColor);
             *          }
             *      }
             *  }
             * }
             */

            /*
             * // If not turning white, remove any white pixels
             * if (subColor != System.Drawing.Color.White)
             * {
             *  // Remove any white pixels
             *  for (int x = 0; x < whitedOut.Width; x++)
             *  {
             *      for (int y = 0; y < whitedOut.Height; y++)
             *      {
             *          if (y >= innerBottomBorder)
             *          {
             *              int whiteThreshold = 150;
             *              Color oldPixel = whitedOut.GetPixel(x, y);
             *              if ((oldPixel.R > whiteThreshold) && (oldPixel.G > whiteThreshold) && (oldPixel.B > whiteThreshold))
             *              {
             *                  whitedOut.SetPixel(x, y, drawingColor);
             *              }
             *          }
             *      }
             *  }
             * }
             */


            // Blank out the entire inside of the card
            for (int x = innerLeft - 1; x <= innerRight + 1; x++)
            {
                for (int y = innerTopBorder; y <= innerBottomBorder; y++)
                {
                    whitedOut.SetPixel(x, y, drawingColor);
                }
            }


            System.Drawing.Rectangle innerImageRect = new System.Drawing.Rectangle(innerLeft, innerTopBorder, innerRight - innerLeft, innerBottomBorder - innerTopBorder);
            System.Drawing.Bitmap    innerImage     = new Bitmap(innerImageRect.Width, innerImageRect.Height);
            innerImage.SetResolution(untouchedImage.HorizontalResolution, untouchedImage.VerticalResolution);
            using (Graphics g = Graphics.FromImage(innerImage))
            {
                g.DrawImage(untouchedImage, 0, 0, innerImageRect, System.Drawing.GraphicsUnit.Pixel);
            }


            //points[0] = new System.Drawing.PointF(15, 15);
            //points[1] = new System.Drawing.PointF(335, 15);
            //points[2] = new System.Drawing.PointF(15, 475);


            // Border should be 4% of the inner-image size
            // innerWidth+0.04%*2 = newWidth;
            // New image needs to be the inner-image-rect + 14 pixel border on all sides
            float widthHeightRatio = (float)innerImageRect.Width / (float)innerImageRect.Height;
            float borderTop        = innerImageRect.Width * 0.048f;
            //float borderSide = borderTop * widthHeightRatio;
            float borderSide = borderTop;
            int   newWidth   = innerImageRect.Width + (int)(borderSide * 2.0f);
            int   newHeight  = innerImageRect.Height + (int)(borderTop * 2.0f);


            //float widthHeightRatio =  (float)innerImageRect.Width / (float)innerImageRect.Height;
            //System.Drawing.PointF[] points = new System.Drawing.PointF[3];
            //points[0] = new System.Drawing.PointF(borderSize, borderSize);
            //points[1] = new System.Drawing.PointF(newWidth - borderSize, borderSize);
            //points[2] = new System.Drawing.PointF(borderSize, (newWidth - (borderSize * 2.0f)) / widthHeightRatio + borderSize);


            // First, scale the image UP to the new size
            System.Drawing.Bitmap scaledUp = new System.Drawing.Bitmap(newWidth, newHeight);
            using (System.Drawing.Graphics graphics = Graphics.FromImage(scaledUp))
            {
                graphics.DrawImage(whitedOut, new System.Drawing.PointF[3]
                {
                    new System.Drawing.PointF(0, 0),
                    new System.Drawing.PointF(newWidth, 0),
                    new System.Drawing.PointF(0, newHeight)
                });
            }

            // Next, re-draw the original inner-image on top of the whited-out version
            using (System.Drawing.Graphics graphics2 = Graphics.FromImage(scaledUp))
            {
                //graphics.DrawImage(untouchedImage, points, innerImageRect, System.Drawing.GraphicsUnit.Pixel);
                //graphics2.DrawImage(innerImage, new System.Drawing.PointF(borderSide, borderTop));
                graphics2.DrawImage(innerImage,
                                    new System.Drawing.RectangleF(new Point((int)borderSide, (int)borderTop), innerImage.Size),
                                    new System.Drawing.RectangleF(new Point(0, 0), innerImage.Size),
                                    System.Drawing.GraphicsUnit.Pixel);

                innerImage.Save("c:\\temp\\InnerOnly.png");
            }

            whitedOut = scaledUp;

            /*
             * // Draw a slight black border around the whole image for cutting purposes
             * for (int x = 0; x < whitedOut.Width; x++)
             * {
             *  for (int y = 0; y < whitedOut.Height; y++)
             *  {
             *      if ((y == whitedOut.Height - 1) || (x == whitedOut.Width - 1) ||
             *          (y == 0) || (x == 0))
             *      {
             *          whitedOut.SetPixel(x, y, Color.FromArgb(255, 200, 200, 200));
             *      }
             *  }
             * }
             */



            return(whitedOut);
        }
Exemple #23
0
		// Converts a bitmap to the specified pixel format.
		public static Bitmap ChangePixelFormat(Bitmap bitmap, PixelFormat format)
		{
			System.Drawing.Rectangle bounds = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);

			return bitmap.Clone(bounds, format);
		}
        /// <summary>
        /// 计算选择区域的缩放比例
        /// </summary>
        /// <param name="MapPbx"></param>
        /// <param name="MapRect"></param>
        /// <param name="SourceImage"></param>
        /// <returns></returns>
        private System.Drawing.Rectangle MapSelectedRegion(FrameworkElement MapPbx, System.Drawing.Rectangle MapRect, System.Drawing.Image SourceImage)
        {
            #region Determine the originally used mapping offsets and dimensions

            int   targetMapOffsetX = 0;
            int   targetMapOffsetY = 0;
            int   targetMapWidth   = 0;
            int   targetMapHeight  = 0;
            float dummyMapRatio    = 0f;
            int   tempWidth        = (int)MapPbx.ActualWidth;
            int   tempHeight       = (int)MapPbx.ActualHeight;
            ImageWork.FixedSize_ResizeRatios(SourceImage.Width, SourceImage.Height, tempWidth, tempHeight, ref targetMapOffsetX, ref targetMapOffsetY, ref targetMapWidth, ref targetMapHeight, ref dummyMapRatio);

            #endregion

            #region Compute mapped .Left and .Width

            double dMapPbxWidth = (double)targetMapWidth;
            double xLeft        = (double)MapRect.Left;
            double xWidth       = (double)MapRect.Width;
            if (targetMapOffsetX > 0)
            {
                double dOffsetX     = (double)targetMapOffsetX;
                double dOffsetWidth = (double)targetMapWidth;
                if (xLeft < dOffsetX)
                {
                    xLeft = 0;
                }
                else
                {
                    xLeft -= dOffsetX;
                }
                double xRight = (double)MapRect.Right - dOffsetX;
                if (xRight > dOffsetWidth)
                {
                    xRight = dOffsetWidth;
                }

                xWidth = xRight - xLeft;
                if (xWidth > dMapPbxWidth)
                {
                    xWidth = dMapPbxWidth;
                }
            }
            int _mappedRect_Left  = (int)((double)SourceImage.Width * (xLeft / dMapPbxWidth));
            int _mappedRect_Width = (int)((double)SourceImage.Width * (xWidth / dMapPbxWidth));
            #endregion

            #region Compute mapped .Top and .Height

            double dMapPbxHeight = (double)targetMapHeight;
            double yTop          = (double)MapRect.Top;
            double yHeight       = (double)MapRect.Height;
            if (targetMapOffsetY > 0)
            {
                double dOffsetY      = (double)targetMapOffsetY;
                double dOffsetHeight = (double)targetMapHeight;
                if (yTop < dOffsetY)
                {
                    yTop = 0;
                }
                else
                {
                    yTop -= dOffsetY;
                }
                double yBottom = (double)MapRect.Bottom - dOffsetY;
                if (yBottom > dOffsetHeight)
                {
                    yBottom = dOffsetHeight;
                }

                yHeight = yBottom - yTop;
                if (yHeight > dMapPbxHeight)
                {
                    yHeight = dMapPbxHeight;
                }
            }
            int _mappedRect_Top    = (int)((double)SourceImage.Height * (yTop / dMapPbxHeight));
            int _mappedRect_Height = (int)((double)SourceImage.Height * (yHeight / dMapPbxHeight));
            #endregion

            return(new System.Drawing.Rectangle(_mappedRect_Left, _mappedRect_Top, _mappedRect_Width, _mappedRect_Height));
        }
        /// <summary>
        /// 剪切图像
        /// </summary>
        /// <param name="sourceImage"></param>
        /// <param name="sourceRect"></param>
        /// <param name="targetWidth"></param>
        /// <param name="targetHeight"></param>
        /// <param name="targetRect"></param>
        /// <param name="bkgColor"></param>
        /// <returns></returns>
        public static System.Drawing.Image ClipImage(System.Drawing.Image sourceImage, System.Drawing.Rectangle sourceRect, int targetWidth, int targetHeight, System.Drawing.Rectangle targetRect, System.Drawing.Color bkgColor)
        {
            System.Drawing.Bitmap returnImage = new System.Drawing.Bitmap(targetWidth, targetHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            //设置目标图像的水平,垂直分辨率
            returnImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

            //创建一个graphics object
            System.Drawing.Graphics grImage = System.Drawing.Graphics.FromImage(returnImage);

            //清除整个绘图面并以指定的背景色填充
            grImage.Clear(bkgColor);

            //指定在缩放或旋转图像时使用的算法
            grImage.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            grImage.DrawImage(sourceImage,
                              targetRect,
                              sourceRect,
                              System.Drawing.GraphicsUnit.Pixel);

            grImage.Dispose();
            return(returnImage);
        }
 /// <summary>
 /// 剪切图片,不需要targetRect参数
 /// </summary>
 /// <param name="sourceImage"></param>
 /// <param name="sourceRect"></param>
 /// <param name="targetWidth"></param>
 /// <param name="targetHeight"></param>
 /// <param name="bkgColor"></param>
 /// <returns></returns>
 public static System.Drawing.Image ClipImage(System.Drawing.Image sourceImage, System.Drawing.Rectangle sourceRect, int targetWidth, int targetHeight, System.Drawing.Color bkgColor)
 {
     System.Drawing.Rectangle targetRect = new System.Drawing.Rectangle(0, 0, targetWidth, targetHeight);
     return(ClipImage(sourceImage, sourceRect, targetWidth, targetHeight, targetRect, bkgColor));
 }
Exemple #27
0
 public static void setBounds(System.Drawing.Rectangle bounds)
 {
     MainWindow.bounds = bounds;
 }
        private void Combine_Image(object sender, RoutedEventArgs e)
        {
            string path    = InputPath_BG.Text;
            int    columns = 0;

            Int32.TryParse(NumOFClumns_BG.Text, out columns);

            if (!path.EndsWith(@"\"))
            {
                path = path + @"\";
            }

            string[] files     = Directory.GetFiles(path, "*.png");
            int      fileCount = files.Length;

            if (fileCount > 0)
            {
                int maxWidth  = 0;
                int maxHeight = 0;

                foreach (string f in files)
                {
                    using (System.Drawing.Image img = System.Drawing.Image.FromFile(f))
                    {
                        maxWidth  = Math.Max(maxWidth, img.Width);
                        maxHeight = Math.Max(maxHeight, img.Height);
                    }
                }

                Console.WriteLine(" \n Largest input image is {0} x {1}.", maxWidth, maxHeight);
                if (fileCount < columns)
                {
                    Console.WriteLine("Single row, reducing column count to match file count.");
                    columns = fileCount;
                }
                int width  = columns * maxWidth;
                int rows   = (fileCount / columns) + ((fileCount % columns > 0) ? 1 : 0);
                int height = rows * maxHeight;

                Console.WriteLine("Output: {0} rows, {1} cols, {2} x {3} resolution.", rows, columns, width, height);
                Bitmap sheet = new Bitmap(width, height);

                using (Graphics gfx = Graphics.FromImage(sheet))
                {
                    int col = 0;
                    int row = 0;
                    foreach (string f in files)
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromFile(f);
                        int x = (col * maxWidth) + (maxWidth / 2 - img.Width / 2);
                        int y = (row * maxHeight) + (maxHeight / 2 - img.Height / 2);
                        System.Drawing.Rectangle srcRect  = new System.Drawing.Rectangle(0, 0, img.Width, img.Height);
                        System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, img.Width, img.Height);
                        gfx.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
                        img.Dispose();
                        col++;
                        if (col == columns)
                        {
                            col = 0;
                            row++;
                        }
                    }
                }
                BGimg   = (System.Drawing.Image)sheet;
                sheetBG = sheet;
            }
        }
        private void CombineCIImage(object sender, RoutedEventArgs e)
        {
            string path    = InputPath_CI.Text;
            int    columns = 0;

            Int32.TryParse(NumOFClumns_CI.Text, out columns);

            if (!path.EndsWith(@"\"))
            {
                path = path + @"\";
            }

            string[] files     = Directory.GetFiles(path, "*.png");
            int      fileCount = files.Length;

            if (fileCount > 0)
            {
                int maxWidth  = 0;
                int maxHeight = 0;

                foreach (string f in files)
                {
                    using (System.Drawing.Image img = System.Drawing.Image.FromFile(f))
                    {
                        maxWidth  = Math.Max(maxWidth, img.Width);
                        maxHeight = Math.Max(maxHeight, img.Height);
                    }
                }


                if (fileCount < columns)
                {
                    columns = fileCount;
                }
                int    width  = columns * maxWidth;
                int    rows   = (fileCount / columns) + ((fileCount % columns > 0) ? 1 : 0);
                int    height = rows * maxHeight;
                Bitmap sheet  = new Bitmap(width, height);
                using (Graphics gfx = Graphics.FromImage(sheet))
                {
                    int col = 0;
                    int row = 0;
                    foreach (string f in files)
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromFile(f);
                        int x = (col * maxWidth) + (maxWidth / 2 - img.Width / 2);
                        int y = (row * maxHeight) + (maxHeight / 2 - img.Height / 2);
                        System.Drawing.Rectangle srcRect  = new System.Drawing.Rectangle(0, 0, img.Width, img.Height);
                        System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, img.Width, img.Height);
                        gfx.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel);
                        img.Dispose();
                        col++;
                        if (col == columns)
                        {
                            col = 0;
                            row++;
                        }
                    }
                }
                CIimg   = (System.Drawing.Image)sheet;
                sheetCI = sheet;
            }
        }
Exemple #30
0
        // Converts a bitmap to the specified pixel format.
        public static Bitmap ChangePixelFormat(Bitmap bitmap, PixelFormat format)
        {
            System.Drawing.Rectangle bounds = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);

            return(bitmap.Clone(bounds, format));
        }
        private static void DrawFillPattern(Graphics g, FillPattern fillPattern)
        {
            Stopwatch sw = Stopwatch.StartNew();

            if (fillPattern == null)
            {
                return;
            }

            float matrixScale = 1000;

            try
            {
                var width = 30;

                var height = 30;

                var rect = new System.Drawing.Rectangle(0, 0, (int)width, (int)height);

                var rect_border = new System.Drawing.Rectangle(0, 0, (int)width - 1, (int)height - 1);
                Pen myPen       = new Pen(System.Drawing.Color.FromArgb(0, 255, 220), 1);

                g.DrawRectangle(myPen, rect_border);

                var centerX = (rect.Left + rect.Left + rect.Width) / 2;

                var centerY = (rect.Top + rect.Top + rect.Height) / 2;

                g.TranslateTransform(centerX, centerY);

                var rectF = new System.Drawing.Rectangle(-1, -1, 2, 2);

                g.FillRectangle(System.Drawing.Brushes.Transparent, rectF);

                g.ResetTransform();

                var fillGrids = fillPattern.GetFillGrids();

                foreach (var fillGrid in fillGrids)
                {
                    var degreeAngle = (float)fillGrid.Angle * 180 / Math.PI;

                    var pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(0, 255, 220))
                    {
                        Width = 1f / matrixScale
                    };

                    float dashLength = 1;

                    var segments = fillGrid.GetSegments();

                    if (segments.Count > 0)
                    {
                        pen.DashPattern = segments
                                          .Select(s => Math.Max(float.Epsilon, Convert.ToSingle(s)))
                                          .ToArray();

                        dashLength = pen.DashPattern.Sum();
                    }

                    g.ResetTransform();

                    var rotateMatrix = new System.Drawing.Drawing2D.Matrix();
                    rotateMatrix.Rotate((float)degreeAngle);

                    var matrix = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1,
                                                                     centerX, centerY);

                    matrix.Scale(matrixScale, matrixScale);

                    matrix.Translate((float)fillGrid.Origin.U,
                                     (float)fillGrid.Origin.V);

                    var backMatrix = matrix.Clone();
                    backMatrix.Multiply(rotateMatrix);
                    matrix.Multiply(rotateMatrix);

                    var offset = (-10) * dashLength;
                    matrix.Translate(offset, 0);
                    backMatrix.Translate(offset, 0);

                    bool   moving_forward = true;
                    bool   moving_back    = true;
                    int    safety         = 500;
                    double alternator     = 0;
                    while (moving_forward || moving_back) // draw segments shifting and offsetting each time
                    {
                        var rectF1 = new RectangleF(-2 / matrixScale, -2 / matrixScale, 4 / matrixScale, 4 / matrixScale);

                        if (moving_forward && LineIntersectsRect(matrix, rect))
                        {
                            g.Transform = matrix;
                            g.DrawLine(pen, new PointF(0, 0), new PointF(100, 0));
                        }
                        else
                        {
                            moving_forward = false;
                        }

                        if (moving_back && LineIntersectsRect(backMatrix, rect))
                        {
                            g.Transform = backMatrix;
                            g.DrawLine(pen, new PointF(0, 0), new PointF(100, 0));
                        }
                        else
                        {
                            moving_back = false;
                        }

                        if (safety == 0)
                        {
                            break;
                        }
                        else
                        {
                            --safety;
                        }

                        matrix.Translate((float)fillGrid.Shift, (float)fillGrid.Offset);
                        backMatrix.Translate(-(float)fillGrid.Shift, -(float)fillGrid.Offset);

                        alternator += fillGrid.Shift;
                        if (Math.Abs(alternator) > Math.Abs(offset))
                        {
                            matrix.Translate(offset, 0);
                            backMatrix.Translate(offset, 0);
                            alternator = 0d;
                        }
                    }
                }

                sw.Stop();
                g.ResetTransform();

                Pen p = new Pen(System.Drawing.Color.Teal);
                p.Width = 1f / matrixScale;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #32
0
		public Rectangle GetBannerFrameRect ()
			{
			Rectangle ButtonFrameRect = GetButtonFrameRect ();
			Rectangle FullScreenRect = GetLogicalScreenBound ();
			System.Drawing.Rectangle GetBannerFrameRect = new System.Drawing.Rectangle (ButtonFrameRect.Width + ButtonFrameRect.X,
				(int) (ButtonFrameRect.Height * NavigationWindowGeometrieYFactor) + ButtonFrameRect.Y - 1,
				 (int) (FullScreenRect.Width * NavigationWindowGeometrieXFactor),
				 (int) (ButtonFrameRect.Height
						* (1.0 - NavigationWindowGeometrieYFactor)) + 1);
			return GetBannerFrameRect;
			}