首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C#中裁剪图像中的空白

在C#中裁剪图像中的空白
EN

Stack Overflow用户
提问于 2011-11-08 13:35:41
回答 1查看 7.9K关注 0票数 3

可能重复: 从图像中删除周围的空白

我正在寻找帮助裁剪在顶部,底部,左边和右边的图像空白。

我已经找到了以下问题/回答如下,但与答案的链接是到第三方网站,这似乎不再是上线。

EN

回答 1

Stack Overflow用户

发布于 2011-11-08 14:31:35

找到一个解决方案这里,但修改了返回代码部分,允许输入一个空图像,在这种情况下,原始图像将被返回。

代码语言:javascript
运行
AI代码解释
复制
class ImageCrop
{
    public static byte[][] GetRGB(Bitmap bmp)
    {
        BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
        IntPtr ptr = bmp_data.Scan0;
        int num_pixels = bmp.Width * bmp.Height, num_bytes = bmp_data.Stride * bmp.Height, padding = bmp_data.Stride - bmp.Width * 3, i = 0, ct = 1;
        byte[] r = new byte[num_pixels], g = new byte[num_pixels], b = new byte[num_pixels], rgb = new byte[num_bytes];
        System.Runtime.InteropServices.Marshal.Copy(ptr, rgb, 0, num_bytes);

        for (int x = 0; x < num_bytes - 3; x += 3)
        {
            if (x == (bmp_data.Stride * ct - padding)) { x += padding; ct++; };
            r[i] = rgb[x]; g[i] = rgb[x + 1]; b[i] = rgb[x + 2]; i++;
        }
        bmp.UnlockBits(bmp_data);
        return new byte[3][] { r, g, b };
    }
    public static Image AutoCrop(Bitmap bmp)
    {
        //Get an array containing the R,G,B components of each pixel
        var pixels = GetRGB(bmp);

        int h = bmp.Height - 1, w = bmp.Width, top = 0, bottom = h, left = bmp.Width, right = 0, white = 0;
        int tolerance = 95; // 95%

        bool prev_color = false;
        for (int i = 0; i < pixels[0].Length; i++)
        {
            int x = (i % (w)), y = (int)(Math.Floor((decimal)(i / w))), tol = 255 * tolerance / 100;
            if (pixels[0][i] >= tol && pixels[1][i] >= tol && pixels[2][i] >= tol) { white++; right = (x > right && white == 1) ? x : right; }
            else { left = (x < left && white >= 1) ? x : left; right = (x == w - 1 && white == 0) ? w - 1 : right; white = 0; }
            if (white == w) { top = (y - top < 3) ? y : top; bottom = (prev_color && x == w - 1 && y > top + 1) ? y : bottom; }
            left = (x == 0 && white == 0) ? 0 : left; bottom = (y == h && x == w - 1 && white != w && prev_color) ? h + 1 : bottom;
            if (x == w - 1) { prev_color = (white < w) ? true : false; white = 0; }
        }
        right = (right == 0) ? w : right; left = (left == w) ? 0 : left;

        //Crop the image
        if (bottom - top > 0)
        {
            Bitmap bmpCrop = bmp.Clone(new Rectangle(left, top, right - left + 1, bottom - top), bmp.PixelFormat);

            return (Bitmap)(bmpCrop);
        }
        else
        {
            return bmp;
        }
    }


}
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8057380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档