1. 程式人生 > >ASP.NET簡單實現APP中使用者個人頭像上傳和裁剪

ASP.NET簡單實現APP中使用者個人頭像上傳和裁剪

 

最近有個微信專案的使用者個人中心模組中,客戶要求使用者頭像不僅僅只是上傳圖片,還需要能對圖片進行裁剪。考慮到flash在IOS和Android上的相容性問題,於是想著能從js這塊入手,在網上發現了devotion博主寫的《適應各瀏覽器圖片裁剪無重新整理上傳js外掛》文章,從中受到些許啟發,以此為參考,進行了簡單的修改。

 

新建一個頁面,程式碼如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>圖片裁剪</title>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
    <link href="../css/jquery.Jcrop.min.css" rel="stylesheet" />
    <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="../js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript" src="../js/imageCropperUpload.js"></script>
    <style type="text/css">
        #test
        {
            width: 100%;
            height: 100%;
            background-color: #000;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 2;
            opacity: 0.8;
            /*相容IE8及以下版本瀏覽器*/
            filter: alpha(opacity=60);
            display: none;
        }

        #fileList
        {
            width: 100%;
            height: 500px;
            /*background-color: #FF0;*/
            margin: auto;
            position: absolute;
            z-index: 3;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            display: none;
            text-align: center;
        }
        #divtest {
            position: absolute;
            z-index: 3;
            display: none;
            bottom: 10px;
            left: 0;
            width: 100%;
        }
        #divCancel
        {
            float: left;
            width: 48px;
            height: 32px;
            line-height: 32px;
            margin: 10px 20px;
            background-color: #fff;
            text-align: center;
            cursor: pointer;
            display: block;
        }
        #divConfirm
        {
            float: right;
            width: 48px;
            height: 32px;
            line-height: 32px;
            margin: 10px 20px;
            background-color: #fff;
            text-align: center;
            cursor: pointer;
            display: block;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            var btn = $("#selectFile");
            btn.click(function () {
                $("#test").show();
                $("#fileList").show();
                $("#divtest").show();
                $("#divCancel").show();
                $("#divConfirm").show();
            });

            $("#divCancel").click(function () {
                $("#test").hide();
                $("#fileList").hide();
                $("#divtest").hide();
            });
            $("#divConfirm").click(function () {
                $("#files").click();
            });

            btn.cropperUpload({
                url: "../ajax/UploadPersonImage.ashx",//服務端處理圖片
                fileSuffixs: ["jpg", "png", "bmp"],
                errorText: "{0}",
                onComplete: function (msg) {
                    $("#divCancel").hide();
                    $("#divConfirm").hide();
                    if (msg == "false") {
                        alert("上傳失敗!");
                        return;
                    }
                    $("#testimg").attr("src", msg);
                },
                cropperParam: {//Jcrop引數設定,除onChange和onSelect不要使用,其他屬性都可用
                    maxSize: [500, 300], //不要小於50,如maxSize:[40,24]
                    minSize: [300, 150], //不要小於50,如minSize:[40,24]
                    bgColor: "black",
                    bgOpacity: .4,
                    allowResize: true,
                    allowSelect: true,
                    animationDelay: 50
                },
                perviewImageElementId: "fileList", //設定預覽圖片的元素id  
                perviewImgStyle: { width: '100%', height: '500px', border: '1px solid #ebebeb'}//設定預覽圖片的樣式  
            });

            var upload = btn.data("uploadFileData");

            $("#files").click(function () {
                upload.submitUpload();
                $("#test").hide();
                $("#fileList").hide();
                $("#divtest").hide();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <!-- 檔案上傳 start -->
        <div style="width: 100%; float: left">
            <input id="selectFile" type="button" value="選擇檔案" />
            <input id="files" type="button" value="上傳截圖" style="display: none;" />
        </div>
        <!-- 檔案上傳 end -->

        <!-- 圖片上傳後展示的地方 start -->
        <div id="testdiv" style="margin-top: 10px; width: 100%;">
            <img alt="" src="" id="testimg" />
        </div>
        <!-- 圖片上傳後展示的地方 end -->

        <!-- 遮罩層 start -->
        <div id="test"></div>
        <div id="fileList">
        </div>
        <div id="divtest">
            <div id="divCancel">取消</div>
            <div id="divConfirm">確定</div>
        </div>
        <!-- 遮罩層 end -->
    </form>
</body>
</html>

 

頁面中jquery.Jcrop.min.css和jquery.Jcrop.min.js是Jcrop外掛必須的一個樣式表文件和js檔案,jquery可以自行下載,然後後面的imageCropperUpload.js檔案是devotion博主寫的外掛,我自己簡單的修改了一下,注意引用順序不要弄錯了,否則不起作用。

 

(function ($) {
    var defaultSettings = {
        url: "uploadImg/",                       //上傳地址  
        fileSuffixs: ["jpg", "png"],             //允許上傳的檔案字尾名列表  
        errorText: "不能上傳字尾為 {0} 的檔案!", //錯誤提示文字,其中{0}將會被上傳檔案的字尾名替換  
        onCheckUpload: function (text) { //上傳時檢查檔案字尾名不包含在fileSuffixs屬性中時觸發的回撥函式,(text為錯誤提示文字)  
        },
        onComplete: function (msg) { //上傳完成後的回撥函式[不管成功或失敗,它都將被觸發](msg為服務端的返回字串) 
            alert(msg);
        },

        onChosen: function (file, obj, fileSize, errorTxt) { /*選擇檔案後的回撥函式,(file為選中檔案的本地路徑;obj為當前的上傳控制元件例項,
                                                                    fileSize為上傳檔案大小,單位KB[只有在isFileSize為true時,此引數才有值],
                                                                     errorTxt為獲取檔案大小時的錯誤文字提示)  */
            //alert(file);  
        },
        cropperParam: {}, //圖片擷取引數設定,此引數即為Jcrop外掛引數
        isFileSize: false,//是否獲取檔案大小
        perviewImageElementId: "",//用於預覽上傳圖片的元素id(請傳入一個div元素的id)  

        perviewImgStyle: null//用於設定圖片預覽時的樣式(可不設定,在不設定的情況下多檔案上傳時只能顯示一張圖片),如{ width: '100px', height: '100px', border: '1px solid #ebebeb' }  
    };


    $.fn.cropperUpload = function (settings) {

        settings = $.extend({}, defaultSettings, settings || {});

        return this.each(function () {
            var self = $(this);

            var upload = new UploadAssist(settings);

            upload.createIframe(this);

            //綁定當前按鈕點選事件  
            self.bind("click", function (e) {
                upload.chooseFile();
            });

            //將上傳輔助類的例項,存放到當前物件中,方便外部獲取  
            self.data("uploadFileData", upload);

            //建立的iframe中的那個iframe,它的事件需要延遲繫結  
            window.setTimeout(function () {
                $(upload.getIframeContentDocument().body).find("input[type='file']").change(function () {
                    if (!this.value) return;
                    var fileSuf = this.value.substring(this.value.lastIndexOf(".") + 1);


                    //檢查是否為允許上傳的檔案  
                    if (!upload.checkFileIsUpload(fileSuf, upload.settings.fileSuffixs)) {
                        upload.settings.onCheckUpload(upload.settings.errorText.replace("{0}", fileSuf));
                        return;
                    }

                    if (upload.settings.isFileSize) {
                        var size = perviewImage.getFileSize(this, upload.getIframeContentDocument());
                        var fileSize, errorTxt;
                        if (size == "error") {
                            errorTxt = upload.errorText;
                        } else {
                            fileSize = size;
                        }
                        //選中後的回撥  
                        upload.settings.onChosen(this.value, this, fileSize, errorTxt);
                    } else {
                        //選中後的回撥  
                        upload.settings.onChosen(this.value, this);
                    }


                    //是否開啟了圖片預覽  
                    if (upload.settings.perviewImageElementId) {
                        var main = perviewImage.createPreviewElement("closeImg", this.value, upload.settings.perviewImgStyle);
                        $("#" + upload.settings.perviewImageElementId).append(main);
                        var div = $(main).children("div").get(0);

                        perviewImage.beginPerview(this, div, upload.getIframeContentDocument(), upload);
                        $("#fileList").children().children("div").css("height", "100%").css("border", "none");
                    }
                });

                //為建立的iframe內部的iframe繫結load事件  
                $(upload.getIframeContentDocument().body.lastChild).on("load", function () {
                    var dcmt = upload.getInsideIframeContentDocument();
                    upload.submitStatus = true;
                    if (dcmt.body.innerHTML) {


                        if (settings.onComplete) {
                            settings.onComplete(dcmt.body.innerHTML);
                        }


                        dcmt.body.innerHTML = "";
                    }
                });
            }, 100);
        });
    };
})(jQuery);


//上傳輔助類
function UploadAssist(settings) {
    //儲存設定
    this.settings = settings;
    //建立的iframe唯一名稱
    this.iframeName = "upload" + this.getTimestamp();
    //提交狀態
    this.submitStatus = true;
    //針對IE上傳獲取檔案大小時的錯誤提示文字
    this.errorText = "請設定瀏覽器一些引數後再上傳檔案,方法如下(設定一次即可):\n請依次點選瀏覽器選單中的\n'工具->Internet選項->安全->可信站點->自定義級別'\n在彈出的自定義級別視窗中找到 'ActiveX控制元件和外掛' 項,將下面的子項全部選為 '啟用' 後,點選確定。\n此時不要關閉當前視窗,再點選 '站點' 按鈕,在彈出的視窗中將下面複選框的 '√' 去掉,然後點選 '新增' 按鈕並關閉當前視窗。\n最後一路 '確定' 完成並重新整理當前頁面。";

    this.jcropApi;
    return this;
}
UploadAssist.prototype = {
    //輔助類構造器
    constructor: UploadAssist,

    //建立iframe
    createIframe: function (/*外掛中指定的dom物件*/elem) {

        var html = "<html>"
        + "<head>"
        + "<title>upload</title>"
        + "<script>"
        + "function getDCMT(){return window.frames['dynamic_creation_upload_iframe'].document;}"
        + "</" + "script>"
        + "</head>"
        + "<body>"
        + "<form method='post' target='dynamic_creation_upload_iframe' enctype='multipart/form-data' action='" + this.settings.url + "'>"
        + "<input type='text' id='x1' name='x1' />"
        + "<input type='text' id='y1' name='y1' />"
        + "<input type='text' id='x2' name='x2' />"
        + "<input type='text' id='y2' name='y2' />"
        + "<input type='text' id='w'  name='w' />"
        + "<input type='text' id='h'  name='h' />"
        + "<input type='text' id='maxW' name='maxW' />"
        + "<input type='text' id='maxH' name='maxH' />"
        + "<input type='file' name='fileUpload' />"
        + "</form>"
        + "<iframe name='dynamic_creation_upload_iframe'></iframe>"
        + "</body>"
        + "</html>";


        this.iframe = $("<iframe name='" + this.iframeName + "'></iframe>")[0];
        this.iframe.style.width = "0px";
        this.iframe.style.height = "0px";
        this.iframe.style.border = "0px solid #fff";
        this.iframe.style.margin = "0px";
        elem.parentNode.insertBefore(this.iframe, elem);
        var iframeDocument = this.getIframeContentDocument();
        iframeDocument.write(html);
    },

    //獲取時間戳
    getTimestamp: function () {
        return (new Date()).valueOf();
    },
    //設定圖片縮放的最大高寬
    setMaxWidthAndHeight: function (/*最大寬*/maxW,/*最大高*/maxH) {
        this.getElement("maxW").value = maxW;
        this.getElement("maxH").value = maxH;
    },
    //設定圖片擷取引數
    setImageCropperObj: function (/*圖片擷取物件*/obj) {
        this.getElement("x1").value = obj.x;
        this.getElement("y1").value = obj.y;
        this.getElement("x2").value = obj.x2;
        this.getElement("y2").value = obj.y2;
        this.getElement("w").value = obj.w;
        this.getElement("h").value = obj.h;
    },
    //獲取建立的iframe中的元素
    getElement: function (id) {
        var dcmt = this.getIframeContentDocument();
        return dcmt.getElementById(id);
    },
    //獲取建立的iframe中的document物件
    getIframeContentDocument: function () {
        return this.iframe.contentDocument || this.iframe.contentWindow.document;
    },

    //獲取建立的iframe所在的window物件
    getIframeWindow: function () {
        return this.iframe.contentWindow || this.iframe.contentDocument.parentWindow;
    },

    //獲取建立的iframe內部iframe的document物件
    getInsideIframeContentDocument: function () {
        return this.getIframeWindow().getDCMT();
    },

    //獲取上傳input控制元件
    getUploadInput: function () {
        var inputs = this.getIframeContentDocument().getElementsByTagName("input");
        var uploadControl;
        this.forEach(inputs, function () {
            if (this.type === "file") {
                uploadControl = this;
                return false;
            }
        });
        return uploadControl;
    },

    //forEach迭代函式
    forEach: function (/*陣列*/arr, /*代理函式*/fn) {
        var len = arr.length;
        for (var i = 0; i < len; i++) {
            var tmp = arr[i];
            if (fn.call(tmp, i, tmp) == false) {
                break;
            }
        }
    },

    //提交上傳
    submitUpload: function () {
        if (!this.submitStatus) return;

        this.submitStatus = false;

        this.getIframeContentDocument().forms[0].submit();
    },

    //檢查檔案是否可以上傳
    checkFileIsUpload: function (fileSuf, suffixs) {

        var status = false;
        this.forEach(suffixs, function (i, n) {
            if (fileSuf.toLowerCase() === n.toLowerCase()) {
                status = true;
                return false;
            }
        });
        return status;
    },


    //選擇上傳檔案
    chooseFile: function () {
        if (this.settings.perviewImageElementId) {
            $("#" + this.settings.perviewImageElementId).empty();
        }

        var uploadfile = this.getUploadInput();
        $(uploadfile).val("").click();
    }
};

//圖片預覽操作
var perviewImage = {
    timers: [],
    //獲取預覽元素
    getElementObject: function (elem) {
        if (elem.nodeType && elem.nodeType === 1) {
            return elem;
        } else {
            return document.getElementById(elem);
        }
    },
    //開始圖片預覽
    beginPerview: function (/*檔案上傳控制元件例項*/file, /*需要顯示的元素id或元素例項*/perviewElemId, /*上傳頁面所在的document物件*/ dcmt, /*上傳輔助類例項*/upload) {
        this.imageOperation(file, perviewElemId, dcmt, upload);
    },
    //圖片預覽操作
    imageOperation: function (/*檔案上傳控制元件例項*/file, /*需要顯示的元素id或元素例項*/perviewElemId, /*上傳頁面所在的document物件*/ dcmt, /*上傳輔助類例項*/upload) {
        for (var t = 0; t < this.timers.length; t++) {
            window.clearInterval(this.timers[t]);
        }
        this.timers.length = 0;

        var tmpParams = {
            onChange: function (c) {
                upload.setImageCropperObj(c);
            },
            onSelect: function (c) {
                upload.setImageCropperObj(c);
            }
        };
        var sWidth = 50, sHeight = 50;
        if (upload.settings.cropperParam.minSize) {
            var size = upload.settings.cropperParam.minSize;
            sWidth = size[0] > sWidth ? size[0] : sWidth;
            sHeight = size[1] > sHeight ? size[1] : sHeight;
        }
        var params = $.extend({}, tmpParams, upload.settings.cropperParam || {});

        var preview_div = this.getElementObject(perviewElemId);

        var MAXWIDTH = preview_div.clientWidth;
        var MAXHEIGHT = preview_div.clientHeight;

        upload.setMaxWidthAndHeight(MAXWIDTH, MAXHEIGHT);

        if (file.files && file.files[0]) { //此處為Firefox,Chrome以及IE10的操作
            preview_div.innerHTML = "";
            var img = document.createElement("img");
            preview_div.appendChild(img);
            img.style.visibility = "hidden";
            img.onload = function () {
                var rect = perviewImage.clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                img.style.width = rect.width + 'px';
                img.style.height = rect.height + 'px';
                img.style.visibility = "visible";
                var offsetWidth = (rect.width / 2) - (sWidth / 2);
                var offsetHeight = (rect.height / 2) - (sHeight / 2);
                var obj = {
                    x: offsetWidth,
                    y: offsetHeight,
                    x2: offsetWidth + sWidth,
                    y2: offsetHeight + sHeight,
                    w: sWidth,
                    h: sHeight
                };

                $(img).Jcrop(params, function () {
                    upload.jcropApi = this;

                    this.animateTo([obj.x, obj.y, obj.x2, obj.y2]);
                    upload.setImageCropperObj(obj);
                });
            };

            var reader = new FileReader();
            reader.onload = function (evt) {
                img.src = evt.target.result;
            };
            reader.readAsDataURL(file.files[0]);
        } else { //此處為IE6,7,8,9的操作
            file.select();
            var src = dcmt.selection.createRange().text;

            var div_sFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + src + "')";
            var img_sFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src='" + src + "')";

            preview_div.innerHTML = "";
            var img = document.createElement("div");
            preview_div.appendChild(img);
            img.style.filter = img_sFilter;
            img.style.visibility = "hidden";
            img.style.width = "100%";
            img.style.height = "100%";

            function setImageDisplay() {
                var rect = perviewImage.clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                preview_div.innerHTML = "";
                var div = document.createElement("div");
                div.style.width = rect.width + 'px';
                div.style.height = rect.height + 'px';
                div.style.filter = div_sFilter;
                var offsetWidth = (rect.width / 2) - (sWidth / 2);
                var offsetHeight = (rect.height / 2) - (sHeight / 2);
                var obj = {
                    x: offsetWidth,
                    y: offsetHeight,
                    x2: offsetWidth + sWidth,
                    y2: offsetHeight + sHeight,
                    w: sWidth,
                    h: sHeight
                };
                preview_div.appendChild(div);
                $(div).Jcrop(params, function () {
                    upload.jcropApi = this;
                    this.animateTo([obj.x, obj.y, obj.x2, obj.y2]);
                    upload.setImageCropperObj(obj);
                });
            }

            //圖片載入計數
            var tally = 0;

            var timer = window.setInterval(function () {
                if (img.offsetHeight != MAXHEIGHT) {
                    window.clearInterval(timer);
                    setImageDisplay();
                } else {
                    tally++;
                }
                //如果超過兩秒鐘圖片還不能載入,就停止當前的輪詢
                if (tally > 20) {
                    window.clearInterval(timer);
                    setImageDisplay();
                }
            }, 100);

            this.timers.push(timer);
        }
    },
    //按比例縮放圖片
    clacImgZoomParam: function (maxWidth, maxHeight, width, height) {
        var param = { width: width, height: height };
        if (width > maxWidth || height > maxHeight) {
            var rateWidth = width / maxWidth;
            var rateHeight = height / maxHeight;

            if (rateWidth > rateHeight) {
                param.width = maxWidth;
                param.height = Math.round(height / rateWidth);
            } else {
                param.width = Math.round(width / rateHeight);
                param.height = maxHeight;
            }
        }

        param.left = Math.round((maxWidth - param.width) / 2);
        param.top = Math.round((maxHeight - param.height) / 2);
        return param;
    },
    //建立圖片預覽元素
    createPreviewElement: function (/*關閉圖片名稱*/name, /*上傳時的檔名*/file, /*預覽時的樣式*/style) {
        var img = document.createElement("div");
        img.title = file;
        img.style.overflow = "hidden";
        for (var s in style) {
            img.style[s] = style[s];
        }

        //var text = document.createElement("div");
        //text.style.width = style.width;
        //text.style.overflow = "hidden";
        //text.style.textOverflow = "ellipsis";
        //text.style.whiteSpace = "nowrap";
        //text.innerHTML = file;

        var main = document.createElement("div");
        main.appendChild(img);
        //main.appendChild(text);
        return main;
    },

    //獲取上傳檔案大小
    getFileSize: function (/*上傳控制元件dom物件*/file, /*上傳控制元件所在的document物件*/dcmt) {
        var fileSize;
        if (file.files && file.files[0]) {
            fileSize = file.files[0].size;
        } else {
            file.select();
            var src = dcmt.selection.createRange().text;
            try {
                var fso = new ActiveXObject("Scripting.FileSystemObject");
                var fileObj = fso.getFile(src);
                fileSize = fileObj.size;
            } catch (e) {
                return "error";
            }
        }
        fileSize = ((fileSize / 1024) + "").split(".")[0];
        return fileSize;
    }
};

然後新建一個一般預處理檔案或者頁面,都可以。以上面的“UploadPersonImage.ashx”為例,程式碼如下:

 

 

    /// <summary>
    /// UploadPersonImage 的摘要說明
    /// </summary>
    public class UploadPersonImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var x = context.Request.Params["x1"];     //水平偏移量
            var y = context.Request.Params["y1"];     //垂直偏移量
            var x2 = context.Request.Params["x2"];    //水平偏移量 + 擷取寬度
            var y2 = context.Request.Params["y2"];    //垂直偏移量 + 擷取高度
            var w = context.Request.Params["w"];      //擷取寬度
            var h = context.Request.Params["h"];      //擷取高度
            var maxW = context.Request.Params["maxW"];//客戶端擷取時,圖片的最大寬度
            var maxH = context.Request.Params["maxH"];//客戶端擷取時,圖片的最大高度

            if (string.IsNullOrEmpty(x) || string.IsNullOrEmpty(y) || string.IsNullOrEmpty(w) || string.IsNullOrEmpty(h) || string.IsNullOrEmpty(maxW) || string.IsNullOrEmpty(maxH))
            {
                context.Response.Write("false");
                return;
            }

            HttpFileCollection files = context.Request.Files;
            if (files == null || files.Count <= 0)
            {
                context.Response.Write("false");
                return;
            }
            // 伺服器端儲存檔案的資料夾(磁碟路徑)
            string path = context.Server.MapPath("/");
            const string imgpath = "WeixinPage/uploadImg"; //儲存地址
            if (Directory.Exists(path + imgpath) == false)
            {
                //如果不存在就建立file資料夾 
                Directory.CreateDirectory(path + imgpath);
            }

            var fileName = string.Empty;
            for (var i = 0; i < files.Count; i++)
            {
                //首先將圖片縮放到與客戶端擷取時的大小一致
                using (var bitmap = GenerateThumbnail(int.Parse(maxW), int.Parse(maxH), files[i].InputStream))
                {
                    fileName = "/" + DateTime.Now.Ticks + ".jpg";
                    var newFileName = path + imgpath + fileName;
                    try
                    {
                        //開始擷取
                        ImageCropper(bitmap, int.Parse(w), int.Parse(h), int.Parse(x), int.Parse(y), newFileName,
                                     System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write("false");
                        return;
                    }
                }
            }

            //上傳成功,輸出圖片相對路徑
            context.Response.Write("../uploadImg" + fileName);

            //上傳失敗
            context.Response.Flush();
        }

        /// <summary>
        /// 生成指定大小的圖片
        /// </summary>
        /// <param name="maxWidth">生成圖片的最大寬度</param>
        /// <param name="maxHeight">生成圖片的最大高度</param>
        /// <param name="imgFileStream">圖片檔案流物件</param>
        private System.Drawing.Bitmap GenerateThumbnail(int maxWidth, int maxHeight, System.IO.Stream imgFileStream)
        {
            using (var img = System.Drawing.Image.FromStream(imgFileStream))
            {
                var sourceWidth = img.Width;
                var sourceHeight = img.Height;

                var thumbWidth = sourceWidth; //要生成的圖片的寬度
                var thumbHeight = sourceHeight; //要生成圖片的的高度

                //計算生成圖片的高度和寬度
                if (sourceWidth > maxWidth || sourceHeight > maxHeight)
                {
                    var rateWidth = (double)sourceWidth / maxWidth;
                    var rateHeight = (double)sourceHeight / maxHeight;

                    if (rateWidth > rateHeight)
                    {
                        thumbWidth = maxWidth;
                        thumbHeight = (int)Math.Round(sourceHeight / rateWidth);
                    }
                    else
                    {
                        thumbWidth = (int)Math.Round(sourceWidth / rateHeight);
                        thumbHeight = maxHeight;
                    }
                }

                var bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight);
                //從Bitmap建立一個System.Drawing.Graphics物件,用來繪製高質量的縮小圖。
                using (var gr = System.Drawing.Graphics.FromImage(bmp))
                {
                    //設定 System.Drawing.Graphics物件的SmoothingMode屬性為HighQuality
                    gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    //下面這個也設成高質量
                    gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    //下面這個設成High
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    //把原始影象繪製成上面所設定寬高的縮小圖
                    var rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
                    gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight,
                                 System.Drawing.GraphicsUnit.Pixel);
                    return bmp;
                }
            }
        }
        /// <summary>
        /// 擷取圖片中的一部分
        /// </summary>
        /// <param name="img">待擷取的圖片</param>
        /// <param name="cropperWidth">擷取圖片的寬</param>
        /// <param name="cropperHeight">擷取圖片的高</param>
        /// <param name="offsetX">水平偏移量</param>
        /// <param name="offsetY">垂直偏移量</param>
        /// <param name="savePath">擷取後的圖片儲存位置</param>
        /// <param name="imgFormat">擷取後的圖片儲存格式</param>
        private void ImageCropper(System.Drawing.Image img, int cropperWidth, int cropperHeight, int offsetX,
                                  int offsetY, string savePath,
                                 System.Drawing.Imaging.ImageFormat imgFormat)
        {
            using (var bmp = new System.Drawing.Bitmap(cropperWidth, cropperHeight))
            {
                //從Bitmap建立一個System.Drawing.Graphics物件,用來繪製高質量的縮小圖。
                using (var gr = System.Drawing.Graphics.FromImage(bmp))
                {
                    //設定 System.Drawing.Graphics物件的SmoothingMode屬性為HighQuality
                    gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    //下面這個也設成高質量
                    gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    //下面這個設成High
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    //把原始影象繪製成上面所設定寬高的擷取圖
                    var rectDestination = new System.Drawing.Rectangle(offsetX, offsetY, cropperWidth, cropperHeight);
                    gr.DrawImage(img, 0, 0, rectDestination,
                                 System.Drawing.GraphicsUnit.Pixel);

                    //儲存擷取的圖片
                    bmp.Save(savePath, imgFormat);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

以上算是基本實現了,下面給出相應的效果圖。

 

Jcrop外掛的下載地址:http://code.ciaoca.com/jquery/jcrop/

參考部落格文章連結地址:http://blog.csdn.net/sq111433/article/details/17562703