只选择位图c#

时间:2017-10-29 08:23:41

标签: c# bitmap

我有一个InkCanvas,我从中得到一个图像并保存这个位图:

RenderTargetBitmap rtb = new RenderTargetBitmap((int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96d, 96d, PixelFormats.Default);
        rtb.Render(inkCanvas);
        BmpBitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(rtb));

        using (FileStream fs = File.Open(NeuralNetwork.Properties.Resources.DrawingFile, FileMode.Create))
        {
            encoder.Save(fs);
        }

该计划的目标是接收一个角色。例如,我画'A'字母: 'A' letter on InkCanvas

我的问题是我需要得到一个区域(矩形)写在这封信的地方。画笔总是黑色,背景总是白色。所以我得到这个图像: 'A' letter with cut edges

所以我很乐意帮助你找到一个有效的算法来做到这一点。先谢谢你!

1 个答案:

答案 0 :(得分:1)

决定关闭issue and post方法,该方法查找最顶部,最右侧,最左侧和最底部的点,以及所说的Dmitry如何将其变成矩形。

    /// <summary>
    /// Select an painted area of canvas by finding the top, the bottom, the right border and the left border of letter.
    /// </summary>
    /// <param name="p"></param>
    /// <returns>An croped image with no white borders.</returns>
    public static Bitmap CalculateRectangle(Bitmap p)
    {
        int TopMost = 0;
        int RightBorder = 0;
        int BotomMost = 0;
        int LeftBorder = 0;
        //maxH
        bool flag = false;
        for (int i = 0; i < p.Height; i++)
        {
            for (int j = 0; j < p.Width; j++)
            {
                if (!IsWhitePixel(p.GetPixel(j, i)))
                {
                    TopMost = i;
                    flag = true;
                    break;
                }
            }
            if (flag) break;
        }
        //minH
        flag = false;
        for (int i = p.Height - 1; i >= 0; i--)
        {
            for (int j = 0; j < p.Width; j++)
            {
                if (!IsWhitePixel(p.GetPixel(j, i)))
                {
                    BotomMost = i;
                    flag = true;
                    break;
                }
            }
            if (flag) break;
        }
        //left
        flag = false;
        for (int j = 0; j < p.Width; j++)
        {
            for (int i = TopMost; i <= BotomMost; i++)
            {
                if (!IsWhitePixel(p.GetPixel(j, i)))
                {
                    LeftBorder = j;
                    flag = true;
                    break;
                }
            }
            if (flag) break;
        }
        //right
        flag = false;
        for (int j = p.Width - 1; j >= 0; j--)
        {
            for (int i = TopMost; i <= BotomMost; i++)
            {
                if (!IsWhitePixel(p.GetPixel(j, i)))
                {
                    RightBorder = j;
                    flag = true;
                    break;
                }
            }
            if (flag) break;
        }
        return CropImage(p, new Rectangle(new System.Drawing.Point(LeftBorder, TopMost), new System.Drawing.Size(RightBorder - LeftBorder + 1, BotomMost - TopMost + 1)));
    }