这是个自己做的demo,要抽成用户控件什么的大家自己发挥了.
ASP.NET页面代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="t.aspx.cs" Inherits="t.t" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Jcrop Demo</title> <link rel="stylesheet" href="css/main.css" type="text/css" /> <link rel="stylesheet" href="css/demos.css" type="text/css" /> <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" /> <link rel="stylesheet" href="css/upload.css" type="text/css" /> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.Jcrop.min.js"></script> <script type="text/javascript" src="js/upload.js"></script> </head> <body> <form id="fom1" runat="server"> <div class="container"> <div class="row"> <div class="span12"> <div class="jc-demo-box"> <div id="preview-pane"> <div class="preview-container"> <asp:Image ID="small" runat="server"/> </div> </div> <div class="description"> <div class="inline-labels" style="display: none;"> X1:<asp:TextBox runat="server" ID="t1" /> Y1:<asp:TextBox runat="server" ID="t2" /> X2:<asp:TextBox runat="server" ID="t3" /> Y2:<asp:TextBox runat="server" ID="t4" /> W1:<asp:TextBox runat="server" ID="t5" /> H1:<asp:TextBox runat="server" ID="t6" /> </div> <div class="inline-labels"> <asp:HiddenField runat="server" ID="x1" /> <asp:HiddenField runat="server" ID="y1" /> <asp:HiddenField runat="server" ID="w" /> <asp:HiddenField runat="server" ID="h" /> </div> <div> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="上传" Width="54px" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="裁剪、压缩" OnClick="Button2_Click" /> <input type="button" onclick="clearImage()" value="清空"/><br /> <asp:Label ID="lb_info" runat="server" Text="" Style="color: Red"></asp:Label> <asp:Image runat="server" ID="Image1" style="width:800px;height:600px;"/> <asp:HiddenField runat="server" ID="hidFileName" /> </div> </div> </div> </div> </div> </div> </form> </body> </html>
Jquery Jcrop js配置 : upload.js
1 jQuery(function ($) { 2 var jcrop_api, 3 boundx, 4 boundy, 5 $preview = $('#preview-pane'), 6 $pcnt = $('#preview-pane .preview-container'), 7 $pimg = $('#preview-pane .preview-container img'), 8 9 xsize = $pcnt.width(), 10 ysize = $pcnt.height(); 11 12 console.log('init', [xsize, ysize]); 13 $('#Image1').Jcrop({ 14 onChange: updatePreview, 15 onSelect: updatePreview, 16 aspectRatio: xsize / ysize 17 }, function () { 18 var bounds = this.getBounds(); 19 boundx = bounds[0]; 20 boundy = bounds[1]; 21 jcrop_api = this; 22 $preview.appendTo(jcrop_api.ui.holder); 23 }); 24 25 function updatePreview(c) { 26 if (parseInt(c.w) > 0) { 27 var rx = xsize / c.w; 28 var ry = ysize / c.h; 29 30 $pimg.css({ 31 width: Math.round(rx * boundx) + 'px', 32 height: Math.round(ry * boundy) + 'px', 33 marginLeft: '-' + Math.round(rx * c.x) + 'px', 34 marginTop: '-' + Math.round(ry * c.y) + 'px' 35 }); 36 } 37 38 $('#x1').val(c.x); 39 $('#y1').val(c.y); 40 $('#x2').val(c.x2); 41 $('#y2').val(c.y2); 42 $('#w').val(c.w); 43 $('#h').val(c.h); 44 45 $('#t1').val(c.x); 46 $('#t2').val(c.y); 47 $('#t3').val(c.x2); 48 $('#t4').val(c.y2); 49 $('#t5').val(c.w); 50 $('#t6').val(c.h); 51 }; 52 }); 53 54 55 function clearImage() { 56 location.href = location.href; 57 }
后台代码:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Web; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 using Image = System.Drawing.Image; 9 10 namespace t 11 { 12 public partial class t : System.Web.UI.Page 13 { 14 protected void Page_Load(object sender, EventArgs e) 15 { 16 17 } 18 19 /// <summary> 20 /// 文件上传 21 /// </summary> 22 protected void Button1_Click(object sender, EventArgs e) 23 { 24 if (FileUpload1.FileName == "") 25 { 26 this.lb_info.Text = "上传文件不能为空"; 27 return; 28 } 29 30 bool fileIsValid = false; 31 //如果确认了上传文件,则判断文件类型是否符合要求 32 if (this.FileUpload1.HasFile) 33 { 34 //获取上传文件的后缀 35 String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower(); 36 String[] restrictExtension = { ".gif", ".jpg", ".bmp", ".png" }; 37 //判断文件类型是否符合要求 38 for (int i = 0; i < restrictExtension.Length; i++) 39 { 40 if (fileExtension == restrictExtension[i]) 41 { 42 fileIsValid = true; 43 } 44 } 45 //如果文件类型符合要求,调用SaveAs方法实现上传,并显示相关信息 46 if (fileIsValid == true) 47 { 48 //上传文件是否大于10M 49 if (FileUpload1.PostedFile.ContentLength > (10 * 1024 * 1024)) 50 { 51 this.lb_info.Text = "上传文件过大"; 52 return; 53 } 54 try 55 { 56 this.Image1.ImageUrl = "~/upload_temporary/" + FileUpload1.FileName; 57 this.small.ImageUrl = "~/upload_temporary/" + FileUpload1.FileName; 58 string saveUrl = Server.MapPath("~/upload_temporary/") + FileUpload1.FileName; 59 this.FileUpload1.SaveAs(saveUrl); 60 this.lb_info.Text = "文件上传成功!"; 61 string newImg = ImageHelper.ReducedImage(800, 600, saveUrl);//裁成高:600px,宽:800px图片 62 int start = newImg.LastIndexOf('\\') + 1; 63 int len = newImg.Length - newImg.LastIndexOf('\\') - 1; 64 string newImgFile = newImg.Substring(start, len); 65 string newImgFileUrl = "~/upload_temporary/" + newImgFile; 66 Image1.ImageUrl = newImgFileUrl; 67 small.ImageUrl = newImgFileUrl; 68 hidFileName.Value = newImg;//共享给裁剪方法用 69 if (File.Exists(saveUrl))//移除原图片 70 { 71 File.Delete(saveUrl); 72 } 73 } 74 catch 75 { 76 this.lb_info.Text = "文件上传失败!"; 77 } 78 finally 79 { 80 81 } 82 } 83 else 84 { 85 this.lb_info.Text = "只能够上传后缀为.gif,.jpg,.bmp,.png的文件"; 86 } 87 } 88 } 89 protected void Button2_Click(object sender, EventArgs e) 90 { 91 if (string.IsNullOrEmpty(x1.Value) && string.IsNullOrEmpty(y1.Value) && string.IsNullOrEmpty(w.Value) && string.IsNullOrEmpty(h.Value)) 92 { 93 this.lb_info.Text = "请先裁剪图片!"; 94 } 95 else 96 { 97 int intX1 = (int)Math.Ceiling(decimal.Parse(x1.Value)); 98 int intY1 = (int)Math.Ceiling(decimal.Parse(y1.Value)); 99 int intW = (int)Math.Ceiling(decimal.Parse(w.Value)); 100 int intH = (int)Math.Ceiling(decimal.Parse(h.Value)); 101 string picResultPath = hidFileName.Value; 102 byte[] imageBytes = ImageHelper.Crop(picResultPath, intW, intH, intX1, intY1); 103 MemoryStream ms = new MemoryStream(imageBytes);//byte[]转换为图片 104 Image img = Image.FromStream(ms); 105 img.Save(picResultPath); 106 this.lb_info.Text += "\r\t裁剪成功!\r\t"; 107 this.lb_info.Text += "压缩成功!"; 108 hidFileName.Value = ""; 109 } 110 } 111 } 112 }
应用了个图片处理类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Drawing; 6 using System.Drawing.Drawing2D; 7 using System.Drawing.Imaging; 8 using Image = System.Drawing.Image; 9 using System.IO; 10 11 namespace t 12 { 13 /// <summary> 14 /// 图片压缩 15 /// </summary> 16 public class ImageHelper 17 { 18 #region 剪裁图像 19 /// <summary> 20 /// 21 /// </summary> 22 /// <param name="Img"></param> 23 /// <param name="Width"></param> 24 /// <param name="Height"></param> 25 /// <param name="X"></param> 26 /// <param name="Y"></param> 27 /// <returns></returns> 28 public static byte[] Crop(string Img, int Width, int Height, int X, int Y) 29 { 30 try 31 { 32 using (var OriginalImage = new Bitmap(Img)) 33 { 34 using (var bmp = new Bitmap(Width, Height, OriginalImage.PixelFormat)) 35 { 36 bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution); 37 using (Graphics Graphic = Graphics.FromImage(bmp)) 38 { 39 Graphic.SmoothingMode = SmoothingMode.AntiAlias; 40 Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 41 Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; 42 Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, Width, Height), X, Y, Width, Height, 43 GraphicsUnit.Pixel); 44 var ms = new MemoryStream(); 45 bmp.Save(ms, OriginalImage.RawFormat); 46 return ms.GetBuffer(); 47 } 48 } 49 } 50 } 51 catch (Exception Ex) 52 { 53 throw (Ex); 54 } 55 } 56 #endregion 57 58 #region 方法1,按大小 59 /// <summary> 60 ///按大小压缩 61 /// </summary> 62 /// <param name="Width">压缩宽</param> 63 /// <param name="Height">压缩高</param> 64 /// <param name="targetFilePath">要压缩的图片路径</param> 65 /// <returns>返回压缩后的图片路径</returns> 66 public static string ReducedImage(int Width, int Height, string targetFilePath) 67 { 68 using (Image ResourceImage = Image.FromFile(targetFilePath)) 69 { 70 Image ReducedImage; 71 Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(delegate { return false; }); 72 ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero); //按大小压缩 73 string newImagePath = targetFilePath.Substring(0, targetFilePath.LastIndexOf("\\") + 1) + Guid.NewGuid().ToString() + ".jpg"; //压缩图片的存储路径 74 ReducedImage.Save(newImagePath, ImageFormat.Jpeg); //保存压缩图片 75 ReducedImage.Dispose(); 76 return newImagePath; //返回压缩图片的存储路径 77 } 78 } 79 #endregion 80 81 #region 方法2,按百分比 缩小60% Percent为0.6 targetFilePath为目标路径 82 /// <summary> 83 /// 按百分比 压缩 84 /// </summary> 85 /// <param name="Percent">缩小比例 缩小60% Percent为0.6 </param> 86 /// <param name="targetFilePath">要压缩的图片路径</param> 87 /// <returns>返回压缩后的图片路径</returns> 88 public static string ReducedImage(double Percent, string targetFilePath) 89 { 90 using (Image ResourceImage = Image.FromFile(targetFilePath)) 91 { 92 Image ReducedImage; 93 Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(delegate { return false; }); 94 int imageWidth = Convert.ToInt32(ResourceImage.Width * Percent); 95 int imageHeight = Convert.ToInt32(ResourceImage.Height * Percent);//等比例缩放 96 ReducedImage = ResourceImage.GetThumbnailImage(imageWidth, imageHeight, callb, IntPtr.Zero); 97 string newImagePath = targetFilePath.Substring(0, targetFilePath.LastIndexOf("\\") + 1) + Guid.NewGuid().ToString() + ".jpg"; //压缩图片的存储路径 98 ReducedImage.Save(newImagePath, ImageFormat.Jpeg); 99 ReducedImage.Dispose(); 100 return newImagePath; 101 } 102 } 103 #endregion 104 } 105 }
在根目录建个存放上传图片的目录:upload_temporary
web.config中在<system.web>节点下添加文件大小参数,不然上传会报错
<httpRuntime targetFramework="4.6.1" executionTimeout="500" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />