How can I crop an image to a circle?

后端 未结 2 1555
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 07:51

I\'m trying to crop an image to a circle, where the area outside of the circle is white.

The new image dimensions would be the same as the original, just effectively

2条回答
  •  孤城傲影
    2021-01-14 08:04

    You need to paint the background to the color that you want first:

    public static Image CropToCircle(Image srcImage, Color backGround)
    {
        Image dstImage = new Bitmap(srcImage.Width, srcImage.Height, srcImage.PixelFormat);
        Graphics g = Graphics.FromImage(dstImage);
        using (Brush br = new SolidBrush(backGround)) {
            g.FillRectangle(br, 0, 0, dstImage.Width, dstImage.Height);
        }
        GraphicsPath path = new GraphicsPath();
        path.AddEllipse(0, 0, dstImage.Width, dstImage.Height);
        g.SetClip(path);
        g.DrawImage(srcImage, 0, 0);
    
        return dstImage;
    }
    

    Test code:

    Image srcImage = Bitmap.FromFile(@"..\..\080.jpg");
    Image dstImage = CropToCircle(srcImage, Color.CadetBlue);
    dstImage.Save(@"..\..\080cropped.jpg", ImageFormat.Jpeg);
    

    Input: enter image description here

    Output: enter image description here

    If you want the outside of the image to be transparent then you need to set the pixel format to be one with an alpha channel (instead of the srcImage's pixel format) and use a background color that includes an all transparent alpha. When you save it, be sure to use a file format that supports alpha (png, for example).

提交回复
热议问题