C# 在C语言中从图像右侧裁剪空白

C# 在C语言中从图像右侧裁剪空白,c#,image,pixel,lockbits,C#,Image,Pixel,Lockbits,我有一些图片,在底部和右侧有很多空白。我想在向用户显示之前裁剪该空白 到目前为止,我已经实现了从底部检测非白色像素。 像素格式为32bppargb 如何正确地从右向左遍历列并检测非白色像素?这将为您提供目标宽度: unsafe int CropRight(BitmapData data) { int targetWidth = data.Width; for (int x = data.Width - 1; x >= 0; x--)

我有一些图片,在底部和右侧有很多空白。我想在向用户显示之前裁剪该空白

到目前为止,我已经实现了从底部检测非白色像素。 像素格式为32bppargb


如何正确地从右向左遍历列并检测非白色像素?

这将为您提供目标宽度:

    unsafe int CropRight(BitmapData data)
    {
        int targetWidth = data.Width;
        for (int x = data.Width - 1; x >= 0; x--)
        {
            bool isWhiteStripe = true;
            for (int y = data.Height - 1; y > 0; y--)
            {
                if (!IsWhite(data, x, y))
                {
                    isWhiteStripe = false;
                    break;
                }
            }

            if (!isWhiteStripe)
                break;
            targetWidth = x;
        }
        return targetWidth;
    }

    int bytesPerPixel = 4; //32BppArgb = 4bytes oer pixel
    int redOffset = 1; // 32BppArgb -> red color is the byte at index 1, alpha is at index 0

    unsafe bool IsWhite(BitmapData data, int x, int y)
    {
        byte* row = (byte*)data.Scan0 + (y * data.Stride) + (x * bytesPerPixel);

        int blue = row[redOffset + 2];
        int green = row[redOffset + 1];
        int red = row[redOffset];

        // is not white?
        if ((blue != 255) || (green != 255) || (red != 255))
        {
            return false;
        }

        return true;
    }
然后,您可以裁剪图像:

它可能会对您有所帮助
    unsafe int CropRight(BitmapData data)
    {
        int targetWidth = data.Width;
        for (int x = data.Width - 1; x >= 0; x--)
        {
            bool isWhiteStripe = true;
            for (int y = data.Height - 1; y > 0; y--)
            {
                if (!IsWhite(data, x, y))
                {
                    isWhiteStripe = false;
                    break;
                }
            }

            if (!isWhiteStripe)
                break;
            targetWidth = x;
        }
        return targetWidth;
    }

    int bytesPerPixel = 4; //32BppArgb = 4bytes oer pixel
    int redOffset = 1; // 32BppArgb -> red color is the byte at index 1, alpha is at index 0

    unsafe bool IsWhite(BitmapData data, int x, int y)
    {
        byte* row = (byte*)data.Scan0 + (y * data.Stride) + (x * bytesPerPixel);

        int blue = row[redOffset + 2];
        int green = row[redOffset + 1];
        int red = row[redOffset];

        // is not white?
        if ((blue != 255) || (green != 255) || (red != 255))
        {
            return false;
        }

        return true;
    }