asp.net實現圖片線上上傳併在線裁剪

来源:http://www.cnblogs.com/lengzhan/archive/2016/11/11/6053363.html
-Advertisement-
Play Games

asp.net實現圖片線上上傳併在線裁剪,線上上傳使用的是uploadify,線上裁剪使用的是jcrop,兩者結合併使用jquery ajax一般處理程式完美結合 ...


1、說明

  接上一篇文章uploadify實現多附件上傳完成後,又突然用到頭像上傳併在線裁剪。在網上找個眾多例子都沒有符合要求的,有一篇文章寫的不錯,就是文旺老兄寫的這篇Asp.Net平臺下的圖片線上裁剪功能的實現,大家可以看一下,寫的真不錯。我就是在參考了他的代碼下,結合uploadify使用一般處理程式實現了這個功能,寫下了這篇在asp.net實現圖片線上上傳併在線裁剪,有點繞口哈,廢話不多說,現奉上代碼,供同學們交流參考,有什麼不對的地方,望請大家多多提提建議,多謝!多謝!

2、組成

  首先說明一下代碼實現所用到的技術,僅供參考:

    開發工具:vs2010

    目標框架:.NET Framework3.5

    jcrop:Jcrop.js v0.9.12

    Uploadify:uploadify-v3.1

    Jquery:jquery-1.9.0.js

  最後我會將整個Demo上傳,如果同學們的電腦上有開發環境可直接打開項目解決方案運行。

3、代碼

  Default.aspx(測試頁面)

<%@ 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>線上裁剪</title>
    <link href="Scripts/jcrop/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
    <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/jquery.uploadify-3.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var jcrop_api, boundx, boundy;

            $("#file_upload").uploadify({
                "auto": true,
                "buttonText": "選擇圖片",
                "swf": "Scripts/uploadify-v3.1/uploadify.swf",
                "uploader": "App_Handler/Uploadify.ashx?action=upload",
                "fileTypeExts": "*.jpg; *.jpeg; *.gif; *.png; *.bmp",
                "fileTypeDesc": "支持的格式:",
                "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").html("<img id=\"imgOriginal\" name=\"imgOriginal\" /><div style=\"overflow: hidden; margin-top: 20px;\"><div style=\"width: 120px; height: 120px; overflow: hidden;\"><img id=\"imgPreview\" /></div><br /><input type=\"button\" id=\"btnImgCut\" onclick=\"cutSaveImg()\" value=\"裁剪並保存圖片\" /></div>");
                        $("#cutimg img").each(function () { $(this).attr("src", row[0]["message"]); });
                        $("#hidImgUrl").val(row[0]["message"]);
                        $('#imgOriginal').Jcrop({
                            onChange: updatePreview,
                            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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="file" id="file_upload" name="file_upload" />
    </div>
    <div id="cutimg">
    </div>
    <asp:HiddenField ID="hidXone" runat="server" />
    <asp:HiddenField ID="hidYone" runat="server" />
    <asp:HiddenField ID="hidXtwo" runat="server" />
    <asp:HiddenField ID="hidYtwo" runat="server" />
    <asp:HiddenField ID="hidImgWidth" runat="server" />
    <asp:HiddenField ID="hidImgHeight" runat="server" />
    <asp:HiddenField ID="hidImgUrl" runat="server" />
    </form>
</body>
</html>

  

Uploadify.ashx(一般處理程式)

<%@ 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 UploadifyUpload : 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(context);
                break;
            case "cutsaveimg":
                //裁剪並保存
                cutsaveimg(context);
                break;
        }
        context.Response.End();
    }

    /// <summary>
    /// 上傳圖片
    /// </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\\";//設置文件的路徑
                string strFileName = "upload" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;
                string strFileUrl = strPath + strFileName;//保存文件路徑
                if (!Directory.Exists(strPath))
                {
                    Directory.CreateDirectory(strPath);
                }
                postedFile.SaveAs(strFileUrl);//先保存源文件

                context.Response.Write("{\"status\":0,\"message\":\"/App_File/Upload/" + strFileName + "\"}");
            }
            else
            {
                context.Response.Write("{\"status\":1,\"message\":\"上傳失敗!\"}");
            }
        }
        else
        {
            context.Response.Write("{\"status\":1,\"message\":\"上傳失敗!\"}");
        }
    }

    /// <summary>
    /// 裁剪並保存圖片
    /// </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 = strImgUrl.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\":\"裁剪成功並保存!\"}");
        }
        catch
        {
            context.Response.Write("{\"status\":1,\"message\":\"裁剪失敗!\"}");
        }
    }
    /// <summary>
    /// 裁剪圖片
    /// </summary>
    /// <param name="intWidth">要縮小裁剪圖片寬度</param>
    /// <param name="intHeight">要縮小裁剪圖片長度</param>
    /// <param name="strOldImgUrl">要處理圖片路徑</param>
    /// <param name="strNewImgUrl">處理完畢圖片路徑</param>
    public void CutGeneratedImage(int intStartX, int intStartY, int intWidth, int intHeight, string strOldImgUrl, string strNewImgUrl)
    {
        //上傳標準圖大小
        int intStandardWidth = 120;
        int intStandardHeight = 120;

        int intReduceWidth = 0; // 縮小的寬度
        int intReduceHeight = 0; // 縮小的高度
        int intCutOutWidth = 0; // 裁剪的寬度
        int intCutOutHeight = 0; // 裁剪的高度
        int level = 100; //縮略圖的質量 1-100的範圍

        //獲得縮小,裁剪大小
        if (intStandardHeight * intWidth / intStandardWidth > intHeight)
        {
            intReduceWidth = intWidth;
            intReduceHeight = intStandardHeight * intWidth / intStandardWidth;
            intCutOutWidth = intWidth;
            intCutOutHeight = intHeight;
        }
        else if (intStandardHeight * intWidth / intStandardWidth < intHeight)
        {
            intReduceWidth = intStandardWidth * intHeight / intStandardHeight;
            intReduceHeight = intHeight;
            intCutOutWidth = intWidth;
            intCutOutHeight = intHeight;
        }
        else
        {
            intReduceWidth = intWidth;
            intReduceHeight = intHeight;
            intCutOutWidth = intWidth;
            intCutOutHeight = intHeight;
        }

        //通過連接創建Image對象
        //System.Drawing.Image oldimage = System.Drawing.Image.FromFile(strOldImgUrl);
        //oldimage.Save(Server.MapPath("tepm.jpg"));
        //oldimage.Dispose();

        //縮小圖片
        Bitmap bm = new Bitmap(strOldImgUrl);

        //處理JPG質量的函數
        ImageCodecInfo[] codecs = ImageCodecInfo.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);

        //裁剪圖片
        Rectangle cloneRect = new Rectangle(intStartX, intStartY, intCutOutWidth, intCutOutHeight);
        PixelFormat format = bm.PixelFormat;
        Bitmap cloneBitmap = bm.Clone(cloneRect, format);

        //保存圖片
        cloneBitmap.Save(strNewImgUrl, ici, ep);
        bm.Dispose();
    }

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

  

4、最後奉上Demo

  ImgJcrop 

 

作者:小路 QQ:2490024434 
出處:http://www.cnblogs.com/lengzhan/ 
本文版權歸【冷戰】和博客園所有,歡迎轉載收藏,未經作者同意須保留此段聲明,否則保留追究法律責任的權利。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前言 最近做了一個電子政務的項目,其中用到了公文簽章和自定義報表,這兩個功能很常用,我就收集到自己的開發框架中了,同時也把實現方法分享給大家。 http://www.learun.cn:8090 線上demo 公文簽章 公文簽章是從網上找的一個JS小插件,原理很簡單,就是把印章放到一個div里,然後 ...
  • 【C#Windows 服務】 《一》初入門 目錄: 1.【C#Windows 服務】 《一》初入門 2.【C#Windows 服務】 《二》INI配置文件 一、工具: VS2015+NET Framework4.5。 二、操作: 1、新建windows服務的項目: 2、修改windows服務相關內容 ...
  • volatile多用於多線程的環境,當一個變數定義為volatile時,讀取這個變數的值時候每次都是從momery裡面讀取而不是從cache讀。這樣做是為了保證讀取該變數的信息都是最新的,而無論其他線程如何更新這個變數。 volatile多用於多線程的環境,當一個變數定義為volatile時,讀取這 ...
  • 摘要:VisualStuio2015 asp.net mvc如何引用ExtJS6,使用BundleConfig。 首先下載ExtJS6.0 gpl版。ExtJS有自己的程式框架,但我們需要asp.net mvc5,ExtJS只用作界面庫。 接下來要把下載好的ExtJS6的核心部分抽取出來,目錄結構是... ...
  • 上一篇貌似少介紹了自定義函數和存儲過程, 因為這兩個也可以使用查詢的方式來實現功能, 這一篇就補上 一、自定義函數的創建和調用 (mysql的) 註意在mysql中, delimiter $$ 這個的使用, 起一個分割功能, 有些編譯器中, 如果不寫這個, 是不會把這些當做方法,存儲過程去處理的, ...
  • 預覽效果 源碼下載地址:http://files.cnblogs.com/files/luoxiaozhao/PrintDemo.rar ...
  • 在寫介面的過程中遇到錯誤:空對象不能轉換為值類型 因為我們使用的是petapoco,經過調試後發現是 object val = cmd.ExecuteScalar() 這一句造成的報錯, val = null 因為我執行的是insert語句,而這個方法的功能是:只返回數據集的第一行第一列 解決方案: ...
  • /// <summary> /// 刷新圖層列表,添加素材子元素時間控制項TimeRange /// </summary> public void RefreshListView() { for (int i = 0; i < lstCoverage.Items.Count; i++) //lstCo ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...