需求:從上傳的圖片中裁剪指定矩形區域(x, y, width, height),回傳裁剪後的圖片。適用於頭像裁剪、縮圖生成等。

核心邏輯:
public static Image CropImage(Image src, Rectangle cropRect) {
Bitmap bmp = new Bitmap(cropRect.Width, cropRect.Height);
using (Graphics g = Graphics.FromImage(bmp)) {
g.DrawImage(src, new Rectangle(0, 0, bmp.Width, bmp.Height),
cropRect, GraphicsUnit.Pixel);
}
return bmp;
}

Action 接收裁剪參數,呼叫工具類,將結果 Bitmap 輸出為 JPEG/PNG 串流回傳 FileContentResult。
可搭配 Jcrop、Cropper.js 等 JS 庫讓使用者在瀏覽器視覺化選取區域,再將座標傳給後端裁剪。