剪切图像的中心

mar*_*zzz 3 c# image image-processing

假设我有一个400x300px的图像,我想在服务器端(C#,.NET 4.0)将其剪切为200x200px.

我该怎么做?使用一种画布并移动它?任何教程/代码示例/建议?

小智 5

尝试这样的事情:

        Bitmap sourceImage = ...;

        int targetWidth = 200;
        int targetHeight = 200;

        int x = sourceImage.Width / 2 - targetWidth / 2;
        int y = sourceImage.Height / 2 - targetHeight / 2;

        Rectangle cropArea = 
            new Rectangle(x, y, targetWidth, targetHeight);

        Bitmap targetImage = 
            sourceImage.Clone(cropArea, sourceImage.PixelFormat);
Run Code Online (Sandbox Code Playgroud)

如果源图像小于目标图像大小,这显然会失败,但你明白了.