How to crop an image using C#?

后端 未结 14 1078
忘掉有多难
忘掉有多难 2020-11-22 05:16

How can I write an application that will crop images in C#?

14条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 05:58

    Simpler than the accepted answer is this:

    public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
    {
        Bitmap nb = new Bitmap(r.Width, r.Height);
        using (Graphics g = Graphics.FromImage(nb))
        {
            g.DrawImage(b, -r.X, -r.Y);
            return nb;
        }
    }
    

    and it avoids the "Out of memory" exception risk of the simplest answer.

    Note that Bitmap and Graphics are IDisposable hence the using clauses.

    EDIT: I find this is fine with PNGs saved by Bitmap.Save or Paint.exe, but fails with PNGs saved by e.g. Paint Shop Pro 6 - the content is displaced. Addition of GraphicsUnit.Pixel gives a different wrong result. Perhaps just these failing PNGs are faulty.

提交回复
热议问题