一直没有深入了解研究c#中的GDI+,仅仅只是在应用中构造缩略图或加一下水印
在今天的项目中,遇到以下的需求
用户在上传图片后,统一调整为64*64;宽高大于64的,从图片中间截取,先不论这种设计合不合理,现在问题出现在对原始图片的裁剪上。



.Net中提供了Image类与Graphics类,这二个类可以达到目的。

 System.Drawing.Image SourceImg = System.Drawing.Image.FromStream(this.FileUpload1.PostedFile.InputStream);
            int SourceImgWidth = SourceImg.Width;  //图片的原始Width
            int SourceImgHeight = SourceImg.Height;  //图片的原始Height
            if ((SourceImgWidth != 64) && (SourceImgHeight != 64))
            {
               
                
                //System.Drawing.Imaging.ImageFormat f = g.RawFormat;
                Bitmap b = new Bitmap(64, 64);   
                Graphics gh = Graphics.FromImage(b);
                gh.DrawImageUnscaledAndClipped(SourceImg, new Rectangle(0, 0, SourceImgWidth, SourceImgHeight));
                gh.SmoothingMode = SmoothingMode.AntiAlias;
                b.Save(@"C:\yy1.jpg");
                gh.Dispose();
                b.Dispose();
                SourceImg.Dispose();
            }

查SDK中对于DrawImageUnscaledAndClipped方法的解释:
在不进行缩放的情况下绘制指定的图像,并在需要时剪辑该图像以适合指定的矩形。 

我的理解是:
gh.DrawImageUnscaledAndClipped(SourceImg, new Rectangle(0, 0, 64, 64));
在源图上剪辑一指定矩形的区域,在Rectangel结构中已经定义了x坐标为0,y坐标为0,
执行上面的代码,生成的图片为


将Retangle中的x坐标稍做修改,为了说明问题,将空白部分用黑色填充了
gh.DrawImageUnscaledAndClipped(SourceImg, new Rectangle(10, 0, 64, 64));
生成的图片

看来Rectangle中的x坐标并不是决定在源图中要裁剪的x坐标值
那到底如何在对一张源图进行裁剪呢?