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;
           }
       }

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

              //通过连接创建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

 
 
 
总代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;

namespace CutImage
{
    public partial class PicView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string picName = "http_imgload.jpg";
            string picPath =  "/UploadFiles/" + picName;
            target.ImageUrl = picPath;
            preview.ImageUrl = picPath;
        }

        protected void saveImg(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                string[] urls = target.ImageUrl.Split('/');
                string _url = urls.Last();

                string tempurl = Path.Combine(Server.MapPath("~/UploadFiles/"), _url);
                int startX = int.Parse(x1.Text);
                int startY = int.Parse(y1.Text);
                int width = int.Parse(Iwidth.Text);
                int height = int.Parse(Iheight.Text);
                ImgReduceCutOut(startX, startY, width, height, tempurl, tempurl);
            }
           
        }

      
        /// <summary>
        /// 缩小裁剪图片
        /// </summary>
        /// <param name="int_Width">要缩小裁剪图片宽度</param>
        /// <param name="int_Height">要缩小裁剪图片长度</param>
        /// <param name="input_ImgUrl">要处理图片路径</param>
        /// <param name="out_ImgUrl">处理完毕图片路径</param>
        public void ImgReduceCutOut(int startX,int startY,int int_Width, int int_Height, string input_ImgUrl, string out_ImgUrl)
        {
            // ===上传标准图大小===
            int int_Standard_Width = 120;
            int int_Standard_Height = 120;

            int Reduce_Width = 0; // 缩小的宽度
            int Reduce_Height = 0; // 缩小的高度
            int CutOut_Width = 0; // 裁剪的宽度
            int CutOut_Height = 0; // 裁剪的高度
            int level = 100; //缩略图的质量 1-100的范围

            // ===获得缩小,裁剪大小===
            if (int_Standard_Height * int_Width / int_Standard_Width > int_Height)
            {
                Reduce_Width = int_Width;
                Reduce_Height = int_Standard_Height * int_Width / int_Standard_Width;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }
            else if (int_Standard_Height * int_Width / int_Standard_Width < int_Height)
            {
                Reduce_Width = int_Standard_Width * int_Height / int_Standard_Height;
                Reduce_Height = int_Height;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }
            else
            {
                Reduce_Width = int_Width;
                Reduce_Height = int_Height;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }

            // ===通过连接创建Image对象===
            System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
            oldimage.Save( Server.MapPath("tepm.jpg"));
            oldimage.Dispose();

             ===缩小图片===
            //System.Drawing.Image thumbnailImage = oldimage.GetThumbnailImage(Reduce_Width, Reduce_Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            Bitmap bm = new Bitmap(Server.MapPath("tepm.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, CutOut_Width, CutOut_Height);
            PixelFormat format = bm.PixelFormat;
            Bitmap cloneBitmap = bm.Clone(cloneRect, format);

            // ===保存图片===
           cloneBitmap.Save(out_ImgUrl, ici, ep);
           bm.Dispose();

        }

        public bool ThumbnailCallback()
        {
            return false;
        }

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值