修剪图像空白并保持纵横比

时间:2017-01-31 18:10:38

标签: wpf c#-4.0

我正在尝试修剪和裁剪图像而没有包围的空白,但我得到的图像的宽高比不等于原始图像。

我在C#中使用以下代码

 public Bitmap TrimImageWhiteSpaces(Bitmap bitmap)
    {
        int w = bitmap.Width;
        int h = bitmap.Height;

        Func<int, bool> isAllWhiteRow = row =>
        {
            for (int i = 0; i < w; i++)
            {
                if (bitmap.GetPixel(i, row).R != 255)
                {
                    return false;
                }
            }
            return true;
        };

        Func<int, bool> isAllWhiteColumn = col =>
        {
            for (int i = 0; i < h; i++)
            {
                if (bitmap.GetPixel(col, i).R != 255)
                {
                    return false;
                }
            }
            return true;
        };

        int leftMost = 0;
        for (int col = 0; col < w; col++)
        {
            if (isAllWhiteColumn(col)) leftMost = col + 1;
            else break;
        }

        int rightMost = w - 1;
        for (int col = rightMost; col > 0; col--)
        {
            if (isAllWhiteColumn(col)) rightMost = col - 1;
            else break;
        }

        int topMost = 0;
        for (int row = 0; row < h; row++)
        {
            if (isAllWhiteRow(row)) topMost = row + 1;
            else break;
        }

        int bottomMost = h - 1;
        for (int row = bottomMost; row > 0; row--)
        {
            if (isAllWhiteRow(row)) bottomMost = row - 1;
            else break;
        }

        if (rightMost == 0 && bottomMost == 0 && leftMost == w && topMost == h)
        {
            return bitmap;
        }

        int croppedWidth = rightMost - leftMost + 1;
        int croppedHeight = bottomMost - topMost + 1;

        try
        {

            Bitmap target = new Bitmap(croppedWidth, croppedHeight);

            using (Graphics g = Graphics.FromImage(target))
            {

                g.DrawImage(bitmap,
                    new RectangleF(0, 0, croppedWidth, croppedHeight),
                    new RectangleF(leftMost, topMost, croppedWidth, croppedHeight),
                    GraphicsUnit.Pixel);
            }

            //target = (Bitmap)FixedSize(target,bitmap.Height, bitmap.Width,false);
            return target;
        }
        catch (Exception ex)
        {
            throw new Exception($"Values are top={topMost} bottom={bottomMost} left={leftMost} right={rightMost}", ex);
        }
    }

这是原始图片 enter image description here

这是我执行代码后获得的图像

enter image description here 所以请问有没有办法在保留原始图像宽高比的情况下修剪图像

0 个答案:

没有答案