Asp.net allows you to upload images online and crop images online,
1. Description
After the previous article uploadify implements multiattachment upload, it suddenly uses the Avatar upload and online cropping. I have found a number of examples on the Internet that do not meet the requirements. One article is well written, that is, this Asp written by wenwang. net platform online image cropping function implementation, you can take a look, write really good. After referring to his code, I used uploadify to use a general handler to implement this function. I wrote this article about online uploading and cropping images in asp.net, I don't want to talk about this nonsense. I am going to provide code for your reference. What's wrong? Please give me more suggestions. Thank you! Thank you!
2. Composition
First, describe the technologies used in code implementation for your reference only:
Development Tool: vs2010
Target framework:. NET Framework3.5
Jcrop: Jcrop. js v0.9.12
Uploadify: uploadify-v3.1
Jquery: jquery-1.9.0.js
Finally, I will upload the entire Demo. If you have a development environment on your computer, you can directly open the project solution to run it.
3. Code
Default. aspx (test page)
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Default. aspx. cs" Inherits = "ImgJcrop. _ Default" %> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <Html xmlns =" http://www.w3.org/1999/xhtml "> <Head runat =" server "> <title> online cropping </title> <link href =" Scripts/jcrop/jquery.Jcrop.css "rel =" stylesheet "type =" text/ <link href = "Scripts/uploadify-v3.1/uploadify.css" rel = "stylesheet" type = "text/css"/> <script src = "Scripts/jquery.1.9.0.min. js "type =" text/javascript "> </script> <script src =" Scripts/jcrop/jquery. jcrop. js "type =" text/javascript "> </script> <script src =" Scripts/uploadify-v3.1/jqu Ery. uploadify-3.1.js "type =" text/javascript "> </script> <script type =" text/javascript ">$ (function () {var jcrop_api, boundx, boundy; $ ("# file_upload "). uploadify ({"auto": true, "buttonText": "select image", "swf": "Scripts/uploadify-v3.1/uploadify.swf", "uploader": "App_Handler/Uploadify. ashx? Action = upload "," fileTypeExts ":"*. jpg ;*. jpeg ;*. gif ;*. png ;*. bmp "," fileTypeDesc ":" supported formats: "," multi ": false," removeCompleted ": false," onUploadStart ": function (file) {$ ("# file_upload-queue "). hide () ;}, "onUploadSuccess": function (file, data, response) {var row = eval ("[" + data + "]"); if (row [0] ["status"] = 0) {$ ("# cutimg" 2.16.html (" <div style = \ "Overflow: hidden; margin-top: 20px; \"> <div style = \ "width: 120px; height: 120px; overflow: hidden; \ "> </div> <br/> <input type = \" button \ "id = \" btnImgCut \ "onclick = \ "cutSaveImg () \ "value = \" crop and save images \ "/> </div>"); $ ("# cutimg img "). each (function () {$ (this ). attr ("src", row [0] ["message"]) ;}); $ ("# hidImgUrl "). val (row [0] ["message"]); $ ('# imgoriginal '). jcrop ({onChange: updatePrev Iew, onSelect: updatePreview, aspectRatio: 1, // maxSize: [120,120], setSelect: [0, 0,120,120]}, function () {var bounds = this. getBounds (); boundx = bounds [0]; boundy = bounds [1]; jcrop_api = this ;});} else {alert (row [0] ["message"]) ;}}); function updatePreview (c) {if (parseInt (c. w)> 0) {var rx = 120/c. w; var ry= 120/c. h; $ ("# imgPreview" ).css ({width: Math. round (rx * boundx) +" Px ", height: Math. round (ry * boundy) + "px", marginLeft: "-" + Math. round (rx * c. x) + "px", marginTop: "-" + Math. round (ry * c. y) + "px"}) ;}$ ("# hidXone "). val (c. x); $ ("# hidYone "). val (c. y); $ ("# hidXtwo "). val (c. hidXtwo); $ ("# hidYtwo "). val (c. hidYtwo); $ ("# hidImgWidth "). val (c. w); $ ("# hidImgHeight "). val (c. h) ;};}); function cutSaveImg () {$. ajax ({type: "post", url: "App_Handler/Uploadify. ashx? Action = cutsaveimg ", data: {strImgUrl: $ (" # imgOriginal ") [0]. src, hidXone: $ ("# hidXone "). val (), hidYone: $ ("# hidYone "). val (), hidImgWidth: $ ("# hidImgWidth "). val (), hidImgHeight: $ ("# hidImgHeight "). val ()}, dataType: "html", success: function (data) {var row = eval ("[" + data + "]"); if (row [0] ["status"] = 0) {} alert (row [0] ["message"]) ;}});} </script>
Uploadify. ashx (General handler)
<% @ WebHandler Language = "C #" Class = "UploadifyUpload" %> using System; using System. collections; using System. data; using System. web; using System. linq; using System. web. services; using System. web. services. protocols; using System. web. sessionState; using System. IO; using System. collections. generic; using System. web. UI. webControls; using System. text; using System. drawing; using System. drawing. imaging; public class U PloadifyUpload: IHttpHandler, IRequiresSessionState {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; context. response. charset = "UTF-8"; string action = context. request ["action"]; switch (action) {case "upload": // upload an Image upload (context); break; case "cutsaveimg ": // crop and save the cutsaveimg (context); break;} context. response. end () ;}/// <summary> /// upload an image // /</Summary> // <param name = "context"> </param> private void upload (HttpContext context) {HttpPostedFile postedFile = context. request. files ["Filedata"]; if (postedFile! = Null) {string fileName, fileExtension; int fileSize; fileName = postedFile. FileName; fileSize = postedFile. ContentLength; if (fileName! = "") {FileExtension = postedFile. fileName. substring (postedFile. fileName. lastIndexOf ('. '); string strPath = context. server. mapPath ("/") + "\ App_File \ Upload \"; // set the file path string strFileName = "upload" + DateTime. now. toString ("yyyyMMddHHmmss") + fileExtension; string strFileUrl = strPath + strFileName; // save the file path if (! Directory. exists (strPath) {Directory. createDirectory (strPath);} postedFile. saveAs (strFileUrl); // first save the source file context. response. write ("{\" status \ ": 0, \" message \ ": \"/App_File/Upload/"+ strFileName + "\"}");} else {context. response. write ("{\" status \ ": 1, \" message \ ": \" Upload Failed! \ "}") ;}} Else {context. Response. Write ("{\" status \ ": 1, \" message \ ": \" Upload Failed! \"}");}} /// <Summary> /// crop and save the image /// </summary> /// <param name = "context"> </param> private void cutsaveimg (HttpContext context) {string strImgUrl = context. request ["strImgUrl"]; string strXone = context. request ["hidXone"]; string strYone = context. request ["hidYone"]; string strImgWidth = context. request ["hidImgWidth"]; string strImgHeight = context. request ["hidImgHeight"]; string [] urls = strI MgUrl. Split ('/'); string str_url = urls. Last (); try {string strOldFiel = context. Server. MapPath ("~ /App_File/Upload/"); string strNewFiel = context. Server. MapPath ("~ /App_File/Cut/"); string strOldUrl = Path. combine (strOldFiel, str_url); string strNewUrl = Path. combine (strNewFiel, "cut" + DateTime. now. toString ("yyyyMMddHHmmss") + ". "+ str_url.Split ('. ') [1]); if (! Directory. exists (strNewFiel) {Directory. createDirectory (strNewFiel);} int intStartX = int. parse (strXone); int intStartY = int. parse (strYone); int intWidth = int. parse (strImgWidth); int intHeight = int. parse (strImgHeight); CutGeneratedImage (intStartX, intStartY, intWidth, intHeight, strOldUrl, strNewUrl); context. response. write ("{\" status \ ": 0, \" message \ ": \" cropping successful and saved! \ "}");} Catch {context. Response. Write ("{\" status \ ": 1, \" message \ ": \" cropping failed! \"}");}} /// <Summary> /// crop the image /// </summary> /// <param name = "intWidth"> reduce the width of the cropped image </param> // /<param name = "intHeight"> length of the cropped image </param> // <param name = "strOldImgUrl"> path of the image to be processed </param> /// <param name = "strNewImgUrl"> processed image path </param> public void CutGeneratedImage (int intStartX, int intStartY, int intWidth, int intHeight, string strOldImgUrl, string strNewImgUrl) {// upload the standard image size int intStandardWidth = 120; int intStandardHeight = 120; int intReduceWidth = 0; // The reduced width is int intReduceHeight = 0; // The reduced height is int intCutOutWidth = 0; // The cropped width is int intCutOutHeight = 0; // The cropped height is int level = 100; // The range of the quality of the thumbnail is reduced by 1-// if (intStandardHeight * intWidth/Th> intHeight) {intReduceWidth = intWidth; intReduceHeight = intStandardHeight * intWidth/intStandardWidth; percent = intWidth; intCutOutHeight = intHeight;} else if (intStandardHeight * intWidth/percent <intHeight) {percent = percent * intHeight/intStandardHeight; intReduceHeight = intHeight; percent = intWidth; intCutOutHeight = intHeight;} else {intReduceWidth = intWidth; intReduceHeight = intHeight; intCutOutWidth = intWidth; intCutOutHeight = intHeight;} // create an Image object through a connection // System. drawing. image oldimage = System. drawing. image. fromFile (strOldImgUrl); // oldimage. save (Server. mapPath ("tepm.jpg"); // oldimage. dispose (); // reduce the image Bitmap bm = new Bitmap (strOldImgUrl); // The ImageCodecInfo [] codecs = ImageCodecInfo function for processing JPG quality. 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 (System. drawing. imaging. encoder. quality, (long) level); // crop the image Rectangle cloneRect = new Rectangle (intStartX, intStartY, intCutOutWidth, intCutOutHeight); PixelFormat format = bm. pixelFormat; Bitmap cloneBitmap = bm. clone (cloneRect, format); // Save the image cloneBitmap. save (strNewImgUrl, ici, ep); bm. dispose ();} public bool IsReusable {get {return false ;}}}
4. Demo provided at the end
ImgJcrop
Author: Paths QQ: 2490024434
Source: http://www.cnblogs.com/lengzhan/
This article is copyrighted by [Cold War] And the blog Park. You are welcome to repost it to your favorites. You must retain this statement without the author's consent. Otherwise, you will be entitled to pursue legal liability.