C#如何实现图片的剪裁并保存
最近需要将一张图片上传并按指定位置剪裁,后来在网上找了一个剪裁图片的插件,但是只有前台没有后端,然后我各种百度,并最终完成,特此写一篇博客略表纪念。
前台我就不说了,用的cropper插件,有兴趣的自己去百度找找吧。毛票票有这个插件。
下面是代码:
HttpPostedFilefile=context.Request.Files["avatar_file"];
stringdatasize=context.Request.Params["avatar_data"];
//{"x":30.003846153846148,"y":16.715384615384625,"height":300.8,"width":300.8,"rotate":0}剪裁之后参数
JavaScriptSerializerjss=newJavaScriptSerializer();
ImgSizeimagesize=jss.Deserialize<ImgSize>(datasize);
byte[]FileByte=SetFileToByteArray(file);//图片数组
stringstrtExtension=System.IO.Path.GetExtension(file.FileName);//图片格式
MemoryStreamms1=newMemoryStream(FileByte);
BitmapsBitmap=(Bitmap)Image.FromStream(ms1);
Rectanglesection=newRectangle(newPoint(imagesize.ToInt(imagesize.x),imagesize.ToInt(imagesize.y)),newSize(imagesize.ToInt(imagesize.width),imagesize.ToInt(imagesize.height)));
BitmapCroppedImage=MakeThumbnailImage(sBitmap,section.Width,section.Height,section.Width,section.Height,section.X,section.Y);
上面代码中用到我自己创建了一个ImgSize类,代码如下:
classImgSize
{
//{"x":30.003846153846148,"y":16.715384615384625,"height":300.8,"width":300.8,"rotate":0}
publicdoublex{get;set;}
publicdoubley{get;set;}
publicdoublewidth{get;set;}
publicdoubleheight{get;set;}
publicintrotate{get;set;}
publicintToInt(doubledoubleValue)
{
returnConvert.ToInt32(doubleValue);
}
}
上面代码中使用到的几个方法:
文件转化:
///<summary>
///将From表单file文件转化为byte数组
///</summary>
///<paramname="File">from提交文件流</param>
///<returns></returns>
privatebyte[]SetFileToByteArray(HttpPostedFileFile)
{
Streamstream=File.InputStream;
byte[]AyyayByte=newbyte[File.ContentLength];
stream.Read(AyyayByte,0,File.ContentLength);
stream.Close();
returnAyyayByte;
}
核心剪裁方法:
///<summary>
///裁剪图片并保存
///</summary>
///<paramname="Image">图片信息</param>
///<paramname="maxWidth">缩略图宽度</param>
///<paramname="maxHeight">缩略图高度</param>
///<paramname="cropWidth">裁剪宽度</param>
///<paramname="cropHeight">裁剪高度</param>
///<paramname="X">X轴</param>
///<paramname="Y">Y轴</param>
publicstaticBitmapMakeThumbnailImage(ImageoriginalImage,intmaxWidth,intmaxHeight,intcropWidth,intcropHeight,intX,intY)
{
Bitmapb=newBitmap(cropWidth,cropHeight);
try
{
using(Graphicsg=Graphics.FromImage(b))
{
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage,newRectangle(0,0,cropWidth,cropHeight),X,Y,cropWidth,cropHeight,GraphicsUnit.Pixel);
ImagedisplayImage=newBitmap(b,maxWidth,maxHeight);
displayImage.Save("E:\\cutimg.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Bitmapbit=newBitmap(b,maxWidth,maxHeight);
returnbit;
}
}
catch(System.Exceptione)
{
throwe;
}
finally
{
originalImage.Dispose();
b.Dispose();
}
}
最后的结果是把存到了E盘根目录下面
以上所述是小编给大家介绍的C#如何实现图片的剪裁并保存,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对毛票票网站的支持!