asp.net MVC4 use Jcrop to crop pictures and upload examples

Source: Internet
Author: User
Tags base64 json static class

Reference to download good css and JS files

The code is as follows Copy Code
<link href= "@Url. Content (" ~/scripts/jcrop/jquery. Jcrop.min.css ")" rel= "stylesheet"/>
<script src= "@Url. Content (" ~/scripts/jcrop/jquery. Jcrop.min.js ")" Type= "Text/javascript" ></script>

Asynchronous, you also need to refer to the Jquery.form.js file

The code is as follows Copy Code
<script src= "@Url. Content (" ~/scripts/jquery.form.js ")" Type= "Text/javascript" ></script>

Layout

The code is as follows Copy Code

<div role= "TabPanel" class= "Tab-pane" id= "div_headportrait" >
@using (Ajax.beginform ("edituserheadportrait", "account", NULL, New Ajaxoptions () {HttpMethod = "POST"}, new {enctype = "Multipart/form-data", id = "form_headportrait"}))
{
@Html. AntiForgeryToken ()
@Html. Hiddenfor (M => m.headportraitdata, new {id = "Imgdata"})
@Html. Hidden ("IMGX")
@Html. Hidden ("Imgy")
@Html. Hidden ("IMGW")
@Html. Hidden ("IMGH")
<div class= "Form-horizontal" >
<div class= "Form-group" >
<div class= "col-lg-3" > Current avatar </div>
<div class= "Col-lg-5" >
<div> set up new avatar </div>
<div> supports JPG, JPEG, GIF, PNG, or BMP formats, which can be cropped in large photos. </div>
<div id= "Btnbrowserpic" > Selection </div> <!--here is the Baidu Webuploader plug-in-->
</div>
<div class= "col-lg-3" > Preview Head </div>
</div>
<div class= "Form-group" >
<div class= "Col-lg-3" >

</div>
<div class= "col-lg-5 div-origin" style= "height:300px;height:300px;" >

</div>
<div class= "Col-lg-3" >
<div style= "width:100px;height:100px;overflow:hidden;margin-left:5px;" >

</div>
</div>
</div>
<div class= "Form-group text-center" >
<input type= "button" value= "Save" id= "Btn_save" class= "btn btn-primary"/>
</div>
</div>
}
</div>

JS Code

The code is as follows Copy Code

var uploader = new Webuploader.uploader ({
SWF: ' @Url. Content ("~/scripts/webuploader-0.1.5/uploader.swf") ',
Server: ' @Url. Action ("Uploadimage", "fileupload") ',
Fileval: ' Imgfile ',
FormData: {resizewidth:300, resizeheight:300},
Pick: ' #btnBrowserPic ',//Select Picture button
Accept: {
Title: ' Images ',
Extensions: ' Gif,jpg,jpeg,bmp,png ',
Mimetypes: ' Image/.gif,.jpg,.jpeg,.bmp,.png '
},
Auto:true,//automatic upload
Multiple:false,//Do not allow multiple files to be uploaded simultaneously
Filenumlimit:1//Current queue number
});
Start uploading
Uploader.on ("Uploadstart", function () {

});
Upload successful
Uploader.on (' uploadsuccess ', function (file, response) {
Specific actions based on the results you return
if (response. Status) {
$ (". Div-origin"). html (' ");
var base64data = "Data:image/bmp;base64," + Response. Data;
Configure Jcrop
$ ("#imgOrigin"). attr ("src", base64data). Jcrop ({
Onchange:setcoordsandimgsize,
Onselect:setcoordsandimgsize,
Aspectratio:1,
Setselect: [50, 50, 150, 150]
});
$ ("#imgCropped"). attr ("src", base64data). css ({width: $ (". Jcrop-holder"). Width () + "px", Height: $ (". Jcrop-holder"). Height () + "px"});
$ ("#imgData"). Val (response. Data);
}
});
Upload failed
Uploader.on ("Uploaderror", function (file) {
Alert ("The picture did not load successfully!") ");
});
Error
Uploader.on ("Error", function () {
Alert ("Only one picture can be uploaded at a time (not a valid picture file)!" ");
});
Upload Complete
Uploader.on ("Uploadcomplete", function () {
Uploader.reset (); Resetting the current queue
});
$ ("#btn_save"). On ("click", Function () {
$form _headportrait.submit ();
});
$form _headportrait.ajaxform ({
DataType: ' JSON ',
Success:function (data) {
After success, perform other actions
}
});
Record the location of the crop
function Setcoordsandimgsize (e) {
var imgx = e.x, imgy = e.y, IMGW = e.w, imgh = e.h;
$ ("#imgX"). Val (IMGX);
$ ("#imgY"). Val (imgy);
$ ("#imgW"). Val (IMGW);
$ ("#imgH"). Val (IMGH);
if (parseint (E.W) > 0) {
var rx = 100/IMGW;
var ry = 100/IMGH;
$ (' #imgCropped '). CSS ({
Width:Math.round (RX * $ (". Jcrop-holder"). Width ()) + ' px ',
Height:Math.round (RY * $ (". Jcrop-holder"). Height ()) + ' px ',
MarginLeft: ' + math.round (RX * imgx) + ' px ',
MarginTop: ' + math.round (ry * imgy) + ' px '
). Show ();
}
}


FileUpload Controller

The code is as follows Copy Code

public class Fileuploadcontroller:controller
{
Get:fileupload
[HttpPost]
Public ActionResult uploadimage (httppostedfilebase imgfile, int? resizewidth, int? resizeheight)
{
Jsonobject jsonobj = new Jsonobject ();
if (imgfile!= null && imgfile.contentlength!= 0)
{
Try
{
Jsonobj.data = Imagehelper.resizeimage (Imgfile.inputstream, Resizewidth.value, Resizeheight.value);
Jsonobj.status = true;
Jsonobj.message = "successful";
}
catch (Exception)
{
Jsonobj.message = "Fail";
}
}
Return Json (Jsonobj, jsonrequestbehavior.allowget);
}
}


Picture Processing class

The code is as follows Copy Code

<summary>
Picture processing
</summary>
public static Class Imagehelper
{
public static string Cropimage (byte[] content, int x, int y, int cropwidth, int cropheight)
{
using (MemoryStream stream = new MemoryStream (content))
{
Return Cropimage (stream, x, Y, Cropwidth, cropheight);
}
}
public static string Cropimage (Stream content, int x, int y, int cropwidth, int cropheight)
{
using (Bitmap Sourcebitmap = new Bitmap (content))
{
Zoom the selected picture
Bitmap Bitsource = new Bitmap (Sourcebitmap, Sourcebitmap.width, sourcebitmap.height);
Rectangle croprect = new Rectangle (x, Y, Cropwidth, cropheight);
using (Bitmap Newbitmap = new Bitmap (Cropwidth, Cropheight))
{
Newbitmap.setresolution (Sourcebitmap.horizontalresolution, sourcebitmap.verticalresolution);
using (Graphics g = graphics.fromimage (Newbitmap))
{
G.interpolationmode = Interpolationmode.highqualitybicubic;
G.smoothingmode = smoothingmode.highquality;
G.pixeloffsetmode = pixeloffsetmode.highquality;
g.compositingquality = compositingquality.highquality;
G.drawimage (Bitsource, New Rectangle (0, 0, Newbitmap.width, newbitmap.height), Croprect, GraphicsUnit.Pixel);
Return Getbitmapbytes (NEWBITMAP);
}
}
}
}
public static string Getbitmapbytes (Bitmap source)
{
ImageCodecInfo codec = Imagecodecinfo.getimageencoders () [4];
EncoderParameters parameters = new EncoderParameters (1);
Parameters. Param[0] = new Encoderparameter (encoder.quality, 100L);
using (MemoryStream tmpstream = new MemoryStream ())
{
Source. Save (Tmpstream, codec, parameters);
byte[] data = new Byte[tmpstream.length];
Tmpstream.seek (0, Seekorigin.begin);
Tmpstream.read (data, 0, (int) tmpstream.length);
string result = convert.tobase64string (data);
return result;
}
}
<summary>
Picture Conversion Base64
</summary>
<param name= "Urlorpath" > Image network address or local path </param>
<returns></returns>
public static string ImageToBase64 (String urlorpath)
{
Try
{
if (Urlorpath.contains ("http"))
{
Uri url = new Uri (Urlorpath);
using (var webClient = new WebClient ())
{
var imgdata = webclient.downloaddata (URL);
using (var ms = new MemoryStream (imgdata))
{
byte[] data = new Byte[ms. Length];
Ms. Seek (0, seekorigin.begin);
Ms. Read (data, 0, Convert.ToInt32 (MS). Length));
String netimage = convert.tobase64string (data);
return netimage;
}
}
}
Else
{
FileStream FileStream = new FileStream (Urlorpath, FileMode.Open);
Stream stream = FileStream as stream;
byte[] data = new Byte[stream. Length];
Stream. Seek (0, seekorigin.begin);
Stream. Read (data, 0, Convert.ToInt32 (stream). Length));
String netimage = convert.tobase64string (data);
return netimage;
}
}
catch (Exception)
{
return null;
}

}
<summary>
Scale pictures proportionally
</summary>
<param name= "Content" ></param>
<param name= "Resizewidth" ></param>
<returns></returns>
public static string Resizeimage (Stream content, int resizewidth, int resizeheight)
{
using (Bitmap Sourcebitmap = new Bitmap (content))
{
int width = sourcebitmap.width,
Height = sourcebitmap.height;
if (Height > resizeheight | | | width > resizewidth)
{
if ((Width * resizeheight) > (height * resizewidth))
{
Resizeheight = (resizewidth * height)/width;
}
Else
{
Resizewidth = (Width * resizeheight)/height;
}
}
Else
{
Resizewidth = width;
Resizeheight = height;
}
Zoom the selected picture
Bitmap Bitsource = new Bitmap (Sourcebitmap, Resizewidth, resizeheight);
Bitsource.setresolution (Sourcebitmap.horizontalresolution, sourcebitmap.verticalresolution);
using (MemoryStream stream = new MemoryStream ())
{
Bitsource.save (stream, imageformat.jpeg);
byte[] data = new Byte[stream. Length];
Stream. Seek (0, seekorigin.begin);
Stream. Read (data, 0, Convert.ToInt32 (stream). Length));
String newimage = convert.tobase64string (data);
return newimage;
}
}
}
}


Effect chart

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.