Wednesday, 11 May 2011

Crop an image to minimum size needed inn .NET

    public static Image Crop(Image p)
    {
        dynamic bitmap = new Bitmap(p);
        dynamic leftMost = int.MaxValue;
        dynamic rightMost = 0;
        dynamic bottomMost = int.MaxValue;
        dynamic topMost = 0;
        dynamic backgroundColour = bitmap.GetPixel(0, 0); // assumes that the background is uniform and that the real picture does not extend to the corner
        // Now search for non background pixels
        for (y = 0; y <= bitmap.Height - 1; y++) {
            for (x = 0; x <= bitmap.Width - 1; x++) {
                dynamic colour = bitmap.GetPixel(x, y);
                //Get the color of the pixel
                if (!colour.Equals(backgroundColour)) {
                    leftMost = Math.Min(leftMost, x);
                    topMost = Math.Max(topMost, y);
                    rightMost = Math.Max(rightMost, x);
                    bottomMost = Math.Min(bottomMost, y);
                }
            }
        }

        dynamic newWidth = rightMost - leftMost;
        dynamic newHeight = topMost - bottomMost;
        dynamic border = 5; // so image won't be too close to edge
        Bitmap imgCropped = new Bitmap(newWidth + 2 * border, newHeight + 2 * border);
        Graphics objGraphics = Graphics.FromImage(imgCropped);
        //set the background color to the same as the original
        objGraphics.Clear(backgroundColour);
        //Calculate the offset at which we must start drawing
        dynamic originTop = border - bottomMost;
        dynamic originLeft = border - leftMost;
        //Draw the original image to your new cropped sized image
        objGraphics.DrawImage(bitmap, originLeft, originTop);
        bitmap.Dispose();
        objGraphics.Dispose();
        //return the Cropped image to the caller
        return imgCropped;
    }

Posted via email from kwhitefoot's posterous

No comments:

Post a Comment

Followers