Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# crop circle in a image or bitmap

Tags:

c#

image

bitmap

I am sure its easy but can't seem to find anyone that has the answer. I have an image and I need to cut a circle or even other shapes out of that image. I need this code to be in .net c#. I am doing this in a class so its not wpf or a winform. I will need to pass x and y pos and the size of the circle.

Other option is AForge, ImageStatistics. I need to get a circle (part of the image) and get StdDev.

Thanks for the help. Andrew

-- update to chris post.

Here is chris post in c#. Not as clean as his but its a start.

 public System.Drawing.Image x(string sourceFile, int circleUpperLeftX, int circleUpperLeftY, int circleDiameter)
    {
        Bitmap SourceImage = new Bitmap(System.Drawing.Image.FromFile(sourceFile));
        Rectangle CropRect = new Rectangle(circleUpperLeftX, circleUpperLeftY, circleDiameter, circleDiameter);
        Bitmap CroppedImage = SourceImage.Clone(CropRect, SourceImage.PixelFormat);
        TextureBrush TB = new TextureBrush(CroppedImage);
        Bitmap FinalImage = new Bitmap(circleDiameter, circleDiameter);
        Graphics G = Graphics.FromImage(FinalImage);
        G.FillEllipse(TB, 0, 0, circleDiameter, circleDiameter);
        return FinalImage;
    }
like image 663
Andrew Avatar asked Jan 20 '23 22:01

Andrew


1 Answers

You can use a TextureBrush. The code below crops the image to a square, then loads that into a texture brush and finally draws an ellipse/circle using that brush:

Private Shared Function CropImageToCircle(ByVal sourceFile As String, ByVal circleUpperLeftX As Integer, ByVal circleUpperLeftY As Integer, ByVal circleDiameter As Integer) As Image
    ''//Load our source image
    Using SourceImage As New Bitmap(Image.FromFile(sourceFile))
        ''//Create a rectangle that crops a square of our image
        Dim CropRect As New Rectangle(circleUpperLeftX, circleUpperLeftY, circleDiameter, circleDiameter)
        ''//Crop the image to that square
        Using CroppedImage = SourceImage.Clone(CropRect, SourceImage.PixelFormat)
            ''//Create a texturebrush to draw our circle with
            Using TB As New TextureBrush(CroppedImage)
                ''//Create our output image
                Dim FinalImage As New Bitmap(circleDiameter, circleDiameter)
                ''//Create a graphics object to draw with
                Using G = Graphics.FromImage(FinalImage)
                    ''//Draw our cropped image onto the output image as an ellipse with the same width/height (circle)
                    G.FillEllipse(TB, 0, 0, circleDiameter, circleDiameter)
                    Return FinalImage
                End Using
            End Using
        End Using
    End Using
End Function
like image 197
Chris Haas Avatar answered Jan 30 '23 08:01

Chris Haas