C#如何完成圖片的剪裁並保管。本站提示廣大學習愛好者:(C#如何完成圖片的剪裁並保管)文章只能為提供參考,不一定能成為您想要的結果。以下是C#如何完成圖片的剪裁並保管正文
最近需求將一張圖片上傳並按指定地位剪裁,後來在網上找了一個剪裁圖片的插件,但是只要前台沒有後端,然後我各種百度,並最終完成,特此寫一篇博客略表留念。
前台我就不說了,用的cropper插件,有興味的自己去百度找找吧。 有這個插件。
上面是代碼:
HttpPostedFile file = context.Request.Files["avatar_file"]; string datasize = context.Request.Params["avatar_data"]; //{"x":30.003846153846148,"y":16.715384615384625,"height":300.8,"width":300.8,"rotate":0} 剪裁之後參數 JavaScriptSerializer jss = new JavaScriptSerializer(); ImgSize imagesize = jss.Deserialize<ImgSize>(datasize); byte[] FileByte = SetFileToByteArray(file);//圖片數組 string strtExtension = System.IO.Path.GetExtension(file.FileName);//圖片格式 MemoryStream ms1 = new MemoryStream(FileByte); Bitmap sBitmap = (Bitmap)Image.FromStream(ms1); Rectangle section = new Rectangle(new Point(imagesize.ToInt(imagesize.x), imagesize.ToInt(imagesize.y)), new Size(imagesize.ToInt(imagesize.width), imagesize.ToInt(imagesize.height))); Bitmap CroppedImage = MakeThumbnailImage(sBitmap, section.Width, section.Height, section.Width, section.Height, section.X, section.Y);
下面代碼中用到我自己創立了一個ImgSize類,代碼如下:
class ImgSize { //{"x":30.003846153846148,"y":16.715384615384625,"height":300.8,"width":300.8,"rotate":0} public double x { get; set; } public double y { get; set; } public double width { get; set; } public double height { get; set; } public int rotate { get; set; } public int ToInt(double doubleValue) { return Convert.ToInt32(doubleValue); } }
下面代碼中運用到的幾個辦法:
文件轉化:
/// <summary> /// 將From表單file文件轉化為byte數組 /// </summary> /// <param name="File">from提交文件流</param> /// <returns></returns> private byte[] SetFileToByteArray(HttpPostedFile File) { Stream stream = File.InputStream; byte[] AyyayByte = new byte[File.ContentLength]; stream.Read(AyyayByte, 0, File.ContentLength); stream.Close(); return AyyayByte; }
中心剪裁辦法:
/// <summary> /// 裁剪圖片並保管 /// </summary> /// <param name="Image">圖片信息</param> /// <param name="maxWidth">縮略圖寬度</param> /// <param name="maxHeight">縮略圖高度</param> /// <param name="cropWidth">裁剪寬度</param> /// <param name="cropHeight">裁剪高度</param> /// <param name="X">X軸</param> /// <param name="Y">Y軸</param> public static Bitmap MakeThumbnailImage(Image originalImage, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y) { Bitmap b = new Bitmap(cropWidth, cropHeight); try { using (Graphics g = Graphics.FromImage(b)) { //清空畫布並以通明背風光填充 g.Clear(Color.Transparent); //在指定地位並且按指定大小繪制原圖片的指定局部 g.DrawImage(originalImage, new Rectangle(0, 0, cropWidth, cropHeight), X, Y, cropWidth, cropHeight, GraphicsUnit.Pixel); Image displayImage = new Bitmap(b, maxWidth, maxHeight); displayImage.Save("E:\\cutimg.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); Bitmap bit = new Bitmap(b, maxWidth, maxHeight); return bit; } } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); b.Dispose(); } }
最後的後果是把存到了E盤根目錄上面
以上所述是給大家引見的C#如何完成圖片的剪裁並保管,希望對大家有所協助,假如大家有任何疑問歡送給我留言,會及時回復大家的,在此也十分感激大家對網站的支持!