前台Jcrop配合后台Graphics实现图片裁剪并上传
Jcrop:一个功能强大的图片裁剪插件
版本:Jcrop v0.9.12
VS版本:vs2015
下载地址:http://code.ciaoca.com/jquery/jcrop/version/Jcrop-0.9.12.zip
本文主要讲的是,在前台通过file选择图片,然后用Jcrop裁剪好图片后,把偏移量等参数传值到后台,在后台通过Graphics进行图片的截取并上传到服务器,显示一下重点代码
HTML 部分
<div class="example"> <img src="" id="target" alt="[Jcrop Example]" width="400"> <div id="preview-pane"> <div class="preview-container"> <img src="" id="cutImgId" class="jcrop-preview" alt="Preview"> </div> </div> </div>
//脚本
$(function () { var api = frameElement.api, W = api.opener; //获取原图片实际的宽高 var img = new Image(); img.src = W.document.getElementById('ImageCropUrl').value; img.onload = function () { imgweight = img.width; imgheight = img.height }; var boundx, boundy, // Grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), xsize = $pcnt.width(), ysize = $pcnt.height(); console.log('init', [xsize, ysize]); $('#target').Jcrop({ onChange: updatePreview, onSelect: updatePreview, aspectRatio: 2 //setSelect: [20, 300, 66, 68] }, function () { var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; jcrop_api = this; $preview.appendTo(jcrop_api.ui.holder); } );
//传递到后台 function saveUploadImg(){ c = jcrop_api.tellSelect(); if (parseInt(c.w) > 0) { $.ajax({ url:'/cartoon-web/contentAffix/cutimageAndSaveAffix', //x和y 是坐标,w和h是宽高 data :{"x":Math.round(c.x * imgweight / 280),"y":Math.round(c.y * imgheight / 350),"w":Math.round(c.w * imgweight / 280),"h":Math.round(c.h * imgheight / 350),"filename":filename,"fileid":fileid,"originalfilename":originalfilename}, dataType:'json', success: function(data){ if(data.result == "success"){ }else{ alert("请选择图片"); } } }); } }
//后台代码
if (uploadFile != null) { Bitmap bmpBase = new Bitmap(uploadFile.InputStream); Bitmap bmpNew = new Bitmap(w,h); var format = bmpBase.PixelFormat; bmpBase.PixelFormat); using (Graphics g = Graphics.FromImage(bmpNew)) { // 用白色清空 g.Clear(Color.White); // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 g.InterpolationMode = InterpolationMode.HighQualityBicubic; // 指定高质量、低速度呈现。 g.SmoothingMode = SmoothingMode.HighQuality; // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。 g.DrawImage(bmpBase, 0, 0, new Rectangle(x, y, w, h), GraphicsUnit.Pixel); Bitmap s = Bitmap.FromHbitmap(bmpNew.GetHbitmap()); MemoryStream stream = new MemoryStream(); //获取裁剪后图片的文件流 bmpNew.Save(stream, ImageFormat.Jpeg); bmpBase.Dispose(); bmpNew.Dispose(); stream.Dispose(); return Content(url); } }