Asp.Net平台下的图片在线裁剪功能的实现

最近项目中有个图片在线裁剪功能,本人查找资料,方法如下:前台展现用jquery.Jcrop实现,后台使用 System.Drawing.Image类来进行裁剪.

1.前台展现实现

网上找到这个jquery.Jcrop,稍看了下,发现它提供的效果完全能满足项目需求.

官方网址:http://deepliquid.com/content/Jcrop.html,感兴趣的朋友可去看看.

页面先引用相关样式和脚本:

 <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.Jcrop.js" type="text/javascript"></script>

页面body部分代码:

 <asp:Label ID="Label1" Text="原始图片" runat="server"></asp:Label><br />
        <asp:Image ID="target" runat="server" />
        <br />
        <asp:Label ID="Label2" runat="server" Text="最终显示效果"></asp:Label>
        <div id="preImg" style="width: 150px; height: 80px; overflow: hidden;">
            <asp:Image ID="preview" alt="Preview" runat="server" />
        </div>

其中ID为preImg的Style的width和height的值是裁剪图片的尺寸,而且要定义这个DIV的overflow:hidden.能够及时看到图片的裁剪效果的关键CSS属性就是它了.

接下来讲讲jquery.Jcrop.js的基本用法,及相关javascript的实现.

首先定义一些临时变量,来保存相关参数

         var jcrop_api, boundx, boundy;

然后给图片的DOM元素绑定Jcrop功能,相关的方法属性看英文就能明白其中的意思.

$('#target').Jcrop({
                   onChange: updatePreview,
                   onSelect: updatePreview,
                   onRelease: clearCoords,
                   aspectRatio: 150 / 80,
                   minSize: _minarray,
                   setSelect: _array
               }, function () {          
                   var bounds = this.getBounds();
                   boundx = bounds[0];
                   boundy = bounds[1];
                    jcrop_api = this;
               });

//此方法是用来及时展现图片裁剪效果

               function updatePreview(c) {
                   if (parseInt(c.w) > 0) {
                       var rx = 150 / c.w;
                       var ry = 80 / c.h;
                       var _width;
                       var _height;
                       if (Math.round(rx * boundx) > $targetImg.width()) {
                           _width = $targetImg.width();
                       }
                       else {
                           _width = Math.round(rx * boundx);
                       }
                       if (Math.round(ry * boundy) > $targetImg.height()) {
                           _height = $targetImg.height();
                       }
                       else {
                           _height = Math.round(ry * boundy);
                       }
                       $('#preview').css({
                           width: _width + 'px',
                           height: _height + 'px',
                           marginLeft: '-' + Math.round(rx * c.x) + 'px',
                           marginTop: '-' + Math.round(ry * c.y) + 'px'
                       });
                   }
                   $('#x1').val(c.x);
                   $('#y1').val(c.y);

                   $('#Iwidth').val(c.w);
                   $('#Iheight').val(c.h);
               };

另一部分前台代码: 

<form id="Form1" runat="server">
        <asp:HiddenField ID="HdnNewImgPath" runat="server" />
        <asp:HiddenField ID="x1" runat="server" />
        <asp:HiddenField ID="y1" runat="server" />
        <asp:HiddenField ID="Iwidth" runat="server" />
        <asp:HiddenField ID="Iheight" runat="server" />
        <br />
        <asp:Button ID="SaveImg" runat="server" Text="裁剪并保存图片" OnClick="saveImg" OnClientClick="return CheckIMG()" />
        </form>

 后台代码的实现:

首先引用相关命名空间

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;

保存按钮的方法,从页面取到相关参数,然后调用裁剪方法.

protected void saveImg(object sender, EventArgs e)
       {
           if (IsPostBack)
           {
               string tempurl = Path.Combine(ConfigAccess.UploadImagePath, _url);
               int startX = int.Parse(x1.Value);
               int startY = int.Parse(y1.Value);
               int width = int.Parse(Iwidth.Value);
               int height = int.Parse(Iheight.Value);
               ImgReduceCutOut(startX, startY, width, height, tempurl, tempurl);
               this.target.Visible = false;
               this.Label1.Visible = false;
               this.SaveImg.Enabled = false;
           }
       }
 

接下是最重要的裁剪方法:

  public void ImgReduceCutOut(int startX, int startY, int int_Width, int int_Height, string input_ImgUrl, string out_ImgUrl)
       {
           // 上传标准图大小
           int int_Standard_Width = 150;
           int int_Standard_Height = 80;

//其实在图片裁剪过程中还可以传更多的参数,如把原始图片缩小了再进行裁剪.本实例中是裁剪后,再裁剪后的图片缩小成150X80
              //通过连接创建Image对象
           System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
           oldimage.Save(Server.MapPath("temp.jpg"));//把原图Copy一份出来,然后在temp.jpg上进行裁剪,最后把裁剪后的图片覆盖原图
           oldimage.Dispose();//一定要释放临时图片,要不之后的在此图上的操作会报错,原因冲突
           Bitmap bm = new Bitmap(Server.MapPath("temp.jpg"));
           //处理JPG质量的函数
           ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
           ImageCodecInfo ici = null;
           foreach (ImageCodecInfo codec in codecs)
           {
               if (codec.MimeType == "image/jpeg")
               {
                   ici = codec;
                   break;
               }
           }
           EncoderParameters ep = new EncoderParameters();
           ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)level);

           // 裁剪图片
           Rectangle cloneRect = new Rectangle(startX, startY, int_Width, int_Height);
           PixelFormat format = bm.PixelFormat;
           Bitmap cloneBitmap = bm.Clone(cloneRect, format);
           if (int_Width > int_Standard_Width)
           {
               //缩小图片
               System.Drawing.Image cutImg = cloneBitmap.GetThumbnailImage(int_Standard_Width, int_Standard_Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
               cutImg.Save(out_ImgUrl, ici, ep);
               cutImg.Dispose();
           }
           else
           {
               //保存图片
               cloneBitmap.Save(out_ImgUrl, ici, ep);
           }
           cloneBitmap.Dispose();
           bm.Dispose();
       }

        public bool ThumbnailCallback()
        {
            return false;
        }
至此,图片在线裁剪功能完成

微笑

主要页面源码:source

posted @ 2011-10-19 10:32  文旺  阅读(9456)  评论(17编辑  收藏  举报