方法如下:
/// < summary> /// 截取一张图片的指定部分 /// < /summary> /// 原始图片Bitmap /// 截取图片的宽度 /// 截取图片的高度 /// 开始截取图片的X坐标 /// 开始截取图片的Y坐标 /// < returns> public static Bitmap GetPartOfImageRec(Bitmap sourceBitmap, int width, int height, int offsetX, int offsetY) { Bitmap resultBitmap = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(resultBitmap)) { Rectangle resultRectangle = new Rectangle(0, 0, width, height); Rectangle sourceRectangle = new Rectangle(0 + offsetX, 0 + offsetY, width, height); g.DrawImage(sourceBitmap, resultRectangle, sourceRectangle, GraphicsUnit.Pixel); } return resultBitmap; }
如果图片是base64或者文件流的话,可以先转为bitmap后再调用该方法
base64:
protected Bitmap Base64StringToBitmap(string base64string) { base64string = HttpUtility.UrlDecode(base64string); base64string = base64string.Replace(" ", "+").Split(',')[1]; //取逗号后面的字符串并将空格换为 + 字符 string fileName = Guid.NewGuid().ToString(); byte[] bt = Convert.FromBase64String(base64string); MemoryStream stream = new MemoryStream(bt); Bitmap bitmap = new Bitmap(stream); //释放资源 stream.Close(); return bitmap; }
文件流:
var files = Request.Files; Bitmap bitmap = new Bitmap(files[0].InputStream);