Search code examples
c#asp.netimage-processinggdi+crop

C# - Crop Transparent/White space


I'm trying to remove all white or transparent pixels from an image, leaving the actual image (cropped). I've tried a few solutions, but none seem to work. Any suggestions or am I going to spend the night writing image cropping code?


Solution

  • public Bitmap CropBitmap(Bitmap original)
    {
        // determine new left
        int newLeft = -1;
        for (int x = 0; x < original.Width; x++)
        {
            for (int y = 0; y < original.Height; y++)
            {
                Color color = original.GetPixel(x, y);
                if ((color.R != 255) || (color.G != 255) || (color.B != 255) || 
                    (color.A != 0))
                {
                    // this pixel is either not white or not fully transparent
                    newLeft = x;
                    break;
                }
            }
            if (newLeft != -1)
            {
                break;
            }
    
            // repeat logic for new right, top and bottom
    
        }
    
        Bitmap ret = new Bitmap(newRight - newLeft, newTop - newBottom);
        using (Graphics g = Graphics.FromImage(ret)
        {
            // copy from the original onto the new, using the new coordinates as
            // source coordinates for the original
            g.DrawImage(...);
        }
    
        return ret
    }
    

    Note that this function will be slow as dirt. GetPixel() is unbelievably slow, and accessing the Width and Height properties of a Bitmap inside a loop is also slow. LockBits would be the proper way to do this - there are tons of examples here on StackOverflow.