Asp. NET uses the Jcrop plug-in to realize the picture upload to cut the function

Source: Internet
Author: User
I. Demand

1. Requirements: On the web side to upload the image function on the basis of increasing the preview picture and crop the picture function.

2. Before the change, the following figure is shown:

3. After changing the function, when click Browse (native input type= ' file ' control) Select picture Upload, you can adjust the size and location of the cropping box, click upload button to achieve crop and upload, click to determine after the cropped picture path assigned to the parent page after the article thumbnail input.

Second, realize 1. Thinking: Using input type= ' The hidden ' server control accepts the wide-high value of the Jcrop clipping marquee and the angular coordinates of the quadrilateral marquee, gets these values in the background and uploads the local path to the image, implements the cropping of the picture through the bitmap and graphics classes, and then saves to the local specified path. 2. Use the Jcrop.js plugin, plugin API interface and help document on his official website Http://code.ciaoca.com/jquery/jcrop/3. Here is the image upload interface code, The main view here is the use of JavaScript code jcrop in the page.

<%@ Page language= "C #" autoeventwireup= "true" codefile= "UpFileBox.aspx.cs" inherits= "Publicpage_upfilebox"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

4. The background code accepts the foreground picture path and the clipping size parameter, realizes the picture to cut and to save. Here we mainly look at the process of Upfile () method.

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using Dingkit;
Using System.Drawing;
Using System.Drawing.Drawing2D;

Using System.Net;
    Public partial class PublicPage_UpFileBox:System.Web.UI.Page {public string FileName = ' ";
    public string FileSize = "";
    public string fileexp = "";
    public string filenewname = "";
    public string FilePath = "";
    public string hint = "";
    public string updirkey = "";
    public string updir = "";
    public string FileType = "";

    public string iskeepoldname = "";
        protected void Page_Load (object sender, EventArgs e) {updir = Cfun.getparam ("Updir");
        FileType = Cfun.getparam ("FileType");
        Iskeepoldname = Cfun.getparam ("Iskeepoldname"); if (! IsPostBack) {}
    ///<summary>///file types allow///</summary>///<param name= "fileexp" > File Types </par 
        Am>///<returns> whether to allow </returns> public static bool Isexpallow (string file_exp,string fileexp) {
        String[] Arr_fileexp;
        Char[] split = {' | ', ', ', ', '};
        Arr_fileexp = File_exp.split (Split, 100); Gets the files in the current directory foreach (string file in Arr_fileexp) {if file.
        ToLower () = = Fileexp.tolower ()) return true;
    return false; ///<summary>///upload pictures///</summary>///<returns></returns> private bool Upfile () {if (PictureUrl.PostedFile.ContentLength = = 0) {lb_picerror.text = ' upload path cannot be empty.
            ";
            Lb_picerror.visible = true;
        return false;
            else {lb_picerror.visible = false; String strFilePath = Pictureurl.postedfile.
            FileName; Gets the last "." in the filename (enclosing path).
            Index fileexp = cfile.getfileexp (strFilePath);
            FileName = Cfile.getfilename (strFilePath);
                Determines whether the type of the file is allowed if (FileType = = "") {if (Cfile.isexpallow (fileexp) = = False)
                    {Lb_picerror.text = "upload failed, picture format must be:" + cfile.file_exp;
    
                    Lb_picerror.visible = true;
                return false;
                } else {if (Isexpallow (FILETYPE,FILEEXP) = False)
                    {Lb_picerror.text = "Upload failed, file format must be:" + FileType;
                    Lb_picerror.visible = true;
                return false;
            Double size = pictureurl.postedfile.contentlength/1024.0; FileSize = size.
            ToString ();
           if (Cfile.issizeallow (PictureUrl.PostedFile.ContentLength.ToString ()) = = False) {Lb_picerror.text = "upload failed, you upload the file size of" + FileSize + "K, the maximum allowable size is:" + cfile.file_sizem;
                Lb_picerror.visible = true; Cfun.jsalert ("Upload failed, you uploaded the file beyond the system allowed.")
                ");
            return false;
            //Here I automatically name the file according to the date and file size, make sure the filename does not repeat DateTime now = DateTime.Now;
            String fName = Cfun.left (FileName, filename.length-1-fileexp.length);
            if (Iskeepoldname = = "1") {filenewname = FName; else {filenewname = FName + "_" + now.
            Dayofyear.tostring () + PictureUrl.PostedFile.ContentLength.ToString (); }//Note: I use Server.MapPath () to take the absolute directory of the current file. In asp.net "" must be replaced by "" "if (Updir = =" Null "| |
            Updir = = "") {updir = Cfile.updir;
            } if (Cfun.left (updir,1) = = @ "/") {Updir = Cfun.right (Updir, updir.length-1); }
            if (cfun.right (updir,1) = = @ "/") {Updir = Cfun.left (Updir, updir.length-1); } FilePath = Updir + "/" + Filenewname + "." + fileexp;//"/" + string fileupdir = Sys Tem.
            Web.HttpContext.Current.Request.PhysicalApplicationPath + "/" + Updir; if (!

            System.IO.Directory.Exists (Fileupdir)) {System.IO.Directory.CreateDirectory (fileupdir);
            } Bitmap B;
            Graphics G; int x11 = Convert.ToInt32 (x1.
            Value); int x22 = Convert.ToInt32 (x2.
            Value); int y11 = Convert.ToInt32 (y1.
            Value); int y22 = Convert.ToInt32 (y2.
            Value);
            int ww = Convert.ToInt32 (w.value);

            int hh = Convert.ToInt32 (h.value); using (System.Drawing.Image img = System.Drawing.Image.FromFile (PictureUrl.PostedFile.FileName))//image.fromfile () Parameter cannot be URI format {b = new Bitmap (WW, HHImg. PixelFormat);//Create Bitmap object B.setresolution of the specified size (img. HorizontalResolution, IMG.                                        verticalresolution);/set Resolution G = Graphics.fromimage (b);       Drawing area G.interpolationmode = Interpolationmode.highqualitybicubic;                         Set graphics high quality interpolation mode g.pixeloffsetmode = Pixeloffsetmode.half; Set pixel cheap rules with high speed sawtooth elimination G.drawimage (IMG, new Rectangle (0, 0, WW, hh), New Rectangle (X11, Y11, WW, hh), GRAPHICSU Nit. Pixel)//To draw a picture with the specified rule to crop img.
            Dispose ();//Free memory} b.save (Fileupdir + "/" + Filenewname + "." + Fileexp);//image.save () Save to specified file or stream
            B.dispose ();
            G.dispose ();
        return true;
            } protected void button1_click (object sender, EventArgs e) {if (upfile () = = True) {
            Lb_success.visible = true;
            Lb_fail.visible = false; Cfun.hidesucchint ();
            hint = "";
            Hint + = "file name: <font color= #990000 >" + FileName + "</font><br>";
            Hint + = "File size: <font color= #990000 >" + FileSize + "kb</font><br>";
        Hint + + "upload path: <font color= #990000 >" + FilePath + "</font><br>";
            else {lb_success.visible = false;
            Lb_fail.visible = true;
            hint = "";
            Hint + = "file name: <font color= #990000 >" + FileName + "</font><br>";
            Hint + = "File size: <font color= #990000 >" + FileSize + "kb</font><br>";
        Hint + + "upload path: <font color= #990000 >" + FilePath + "</font><br>";
 }
    }
}
Third, summary

Summarize the problems encountered during the process:

1. Foreground to the background value: You can use the input type= ' hidden ' Add runat= ' Server ' property programming server control, use JS to assign values to the control, the background to accept the control value;

2. Backstage to the foreground to pass value: In the background to define a public variable, the foreground through JS to obtain the variable, such as var filepath = ' <%=FilePath%> ';

3. Background image.fromfile (path) parameter does not support URI format problem: The path of image.fromfile (path) should be a local file path, get input type= ' Value of file ', such as Pictureurl. Postedfile.filename

3. Troubleshooting the background Image.FromFile (path) parameter does not support URI format issues: If you must pass in a URL, use the Image.fromstream () method instead, for example:

HttpWebRequest request = (HttpWebRequest) webrequest.create (URL);
WebResponse response = Request. GetResponse ()//Get response
Image img = image.fromstream (response. GetResponseStream ());///instantiation, get img

4. Two ways to save a file to a specified directory:

4.1) PictureUrl.PostedFile.SaveAs (Fileupdir + "/" + Filenewname + "." + Fileexp); Input id= ' pictureurl ' type= ' file ' runat= ' server ' control uses SaveAs ()

4.2) b. Save (Fileupdir + "/" + Filenewname + "." + Fileexp);//image.save () to the specified file or stream

5. The software uses the Artdialog dialog box component, many times when we take over a new project, we need to understand the basic use of his components, dialog box components should include the function of the parent-child page transfer value, be good at using the various tools at hand;

6. Many times you should comb the logic and debug JavaScript scripts to be good at using alert () and Console.log ().

7. Many times should learn to refuse.







Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.