[原創]ASP.NET MVC調用美圖秀秀開放平台拼圖實現


項目中涉及到圖片的美化和拼接的功能,於是用了美圖秀秀開放平台的api

美圖秀秀開放平台地址:http://open.web.meitu.com/

具體步驟如下:

1.創建MeiTuUpload.aspx視圖頁面:

頁面代碼:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>圖片編輯</title>
    <% List<NewTang.Models.Entity.PicInfo> pics = new List<NewTang.Models.Entity.PicInfo>();
       if (ViewData["Pics"] != null)
       { 
            pics=(List<NewTang.Models.Entity.PicInfo>)ViewData["Pics"];
       }

         %>
 <script src="http://open.web.meitu.com/sources/xiuxiu.js" type="text/<span class="wp_keywordlink_affiliate"><a href="http://www.mikel.cn/category/%e5%bc%80%e5%8f%91%e7%ac%94%e8%ae%b0/javascript" title="JavaScript" target="_blank">JavaScript</a></span>"></script>       
<script language="<span class="wp_keywordlink_affiliate"><a href="http://www.mikel.cn/category/%e5%bc%80%e5%8f%91%e7%ac%94%e8%ae%b0/javascript" title="JavaScript" target="_blank">JavaScript</a></span>" type="text/javascript" >
window.onload=function(){
    xiuxiu.setFlashvars("localFileEnabled", 1);
    xiuxiu.embedSWF("altContent",2,"100%","100%");
    /*第1個參數是加載編輯器div容器,第2個參數是編輯器類型,第3個參數是div容器寬,第4個參數是div容器高*/

    xiuxiu.setUploadURL("http://localhost:4657/Components/stream.ashx"); //修改為您自己的上傳接收圖片程序
    xiuxiu.onInit = function ()
    {
        <% if(pics.Count>0){ %>
        xiuxiu.loadPhoto("<%=pics[0].Path %>");
        <%} %>
    }    
    xiuxiu.onUploadResponse = function (data)
    {
         //alert("上傳響應" + data);  
         parent.setfilePath(data);
         parent.meitu.close();
    }
    xiuxiu.onClose = function() {
        parent.meitu.close();
    }
}

    function closewbox() {
        
    }
    
    function setfilePath(data)
    {
       
    }
</script>
<style type="text/css">
    html, body { height:100%; overflow:hidden; }
    body { margin:0; }
</style>  
</head>
<body >
<form id="upload" action="/Shop/UpLoadImage" method="post"
enctype="multipart/form-data">
<div id="altContent">

    <h1>美圖秀秀</h1>
</div>
</form>
</body>
</html>

2.創建MeiTuUpload的Action
代碼如下:

/// <summary>
/// 美圖秀秀拼圖
/// </summary>
/// <param name="newsInfoId"></param>
/// <returns></returns>
public ActionResult MeiTuUpload(string newsInfoId)
{
    try
    {
        ViewData["title"] = "美圖拼圖";
        PicInfo pic = new PicInfo();
        pic.NewsInfoId = newsInfoId;
        ViewData["Pics"] = business.Select<PicInfo>(pic);
        //主題信息
        NewsInfo news = new NewsInfo() { NewsInfoID=newsInfoId };
        ViewData["News"] = business.Select<NewsInfo>(news);
        

    }
    catch (Exception e)
    {
        return new BaseController().Error("Error", "錯誤信息", e.Message);
    }
    return View();

}

 3.創建文件上傳stream.ashx文件,可以從官方下載:備注:setUploadURL(“”) 參數為接收圖片文件。php示例可參考 流式上傳 或者 標准表單上傳C#示例可參考 流式上傳 或者 標准表單上傳
代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;
using System.IO;
using System.Drawing;
using XiuXiuWeb.XiuXiuStream;

namespace XiuXiuWeb
{
    /// <summary>
    /// Summary description for stream
    /// </summary>
    public class stream : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //config 配置節點可以將圖片保存至指定目錄,未配置將保存至 /XiuXiuUpload
            //<appSettings>
            //  <add key="XiuXiuImageSavePath" value="/upload"/>
            //</appSettings>
            string name = null;
            if (context.Request.TotalBytes > 0)
            {
                XiuXiuStreamImage img = new XiuXiuStreamImage(context);
                name = img.Save();
            }
            else
            {
                name = "非法訪問";
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(name);
        }

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

    namespace XiuXiuStream
    {

        /// <summary>
        /// 上傳抽象類
        /// </summary>
        public abstract class XiuXiuImage
        {

            public String ImageUrl { get;set;}
            /// <summary>
            /// 基類保存
            /// </summary>
            /// <returns>返回保存路徑+文件名</returns>
            public virtual string Save()
            {
                string fileName = this.GetFileName();
                if (null == fileName) return null;

                //string root = HttpContext.Current.Server.MapPath(path);
                string thisDate = "";
                thisDate = DateTime.Now.Year.ToString();
                if (DateTime.Now.Month < 10)
                {
                    thisDate += "0" + DateTime.Now.Month.ToString();
                }
                else
                {
                    thisDate += DateTime.Now.Month.ToString();
                }
                if (DateTime.Now.Day < 10)
                {
                    thisDate += "0" + DateTime.Now.Day.ToString();
                }
                else
                {
                    thisDate += DateTime.Now.Day.ToString();
                }
                string relativePath = System.Web.HttpContext.Current.Server.MapPath(ConfigurationSettings.AppSettings["UploadDirectory"] + "pic/" + thisDate.ToString().Replace(" ", ""));
                if (!Directory.Exists(relativePath))
                {
                    Directory.CreateDirectory(relativePath);
                }
                //if (!Directory.Exists(root))
                //{
                //    Directory.CreateDirectory(root);
                //}
                this.ImageUrl=ConfigurationSettings.AppSettings["WebSiteUrl"] + "/UploadFiles/pic/" + thisDate.ToString().Replace(" ", "") + "/" + fileName;

                this.FileName = Path.Combine(relativePath, fileName);
                string[] paths = { relativePath, fileName };
                return string.Join("/", paths);
            }

            public XiuXiuImage()
            {
                path = path == null ? "/XiuXiuUpload" : path;
            }

            /// <summary>
            /// 確定上傳類型
            /// </summary>
            protected bool IsUplodType
            {
                get
                {
                    string extension = this.GetExtension();
                    return ".jpg .gif .png .icon .bmp .tiff .wmf .emf .exif".IndexOf(extension) >= 0 ? true : false;
                }
            }
            private string _fileName = null;
            /// <summary>
            /// 最終保存路徑
            /// </summary>
            protected string FileName
            {
                set { _fileName = value; }
                get { return _fileName; }
            }

            /// <summary>
            /// 配置文件路徑 無配置上傳到XiuXiuUpload
            /// </summary>
            protected string path = ConfigurationManager.AppSettings["UploadDirectory"];

            /// <summary>
            /// 獲取拓展名
            /// </summary>
            /// <returns></returns>
            protected abstract string GetExtension();

            /// <summary>
            /// 獲取最終保存文件名
            /// </summary>
            /// <returns></returns>
            protected string GetFileName()
            {
                string extension = this.GetExtension();
                if (null == extension) return null;
                else
                {
                    string name = this.GetName();
                    string[] imgName = { "news", name, extension };
                    return string.Join("", imgName);
                }
            }
            /// <summary>
            /// 獲取保存文件名
            /// </summary>
            /// <returns></returns>
            private string GetName()
            {
                DateTime uploadTime = DateTime.Now;
                string[] times = { uploadTime.Year.ToString(), uploadTime.Month.ToString(), uploadTime.Day.ToString(),
                                 uploadTime.Hour.ToString(), uploadTime.Millisecond.ToString(), uploadTime.Second.ToString() };
                return string.Join("", times);
            }
        }
        /// <summary>
        /// Stream接收
        /// </summary>
        public sealed class XiuXiuStreamImage : XiuXiuImage
        {
            private MemoryStream stream = null;

            //圖片的url路徑
            private String webPath=null;

            public XiuXiuStreamImage(HttpContext context)
            {
                int count = context.Request.TotalBytes;
                if (count > 0)
                {
                    byte[] bytes = context.Request.BinaryRead(context.Request.TotalBytes);
                    this.stream = new MemoryStream(bytes);
                }
            }

            private Image File
            {
                get
                {
                    return this.stream == null ? null : Image.FromStream(this.stream);
                }
            }
            /// <summary>
            /// 保存圖片,成功返回文件路徑,失敗null
            /// 非圖片格式返回錯誤信息
            /// </summary>
            /// <returns>成功返回文件路徑 失敗null</returns>
            public override string Save()
            {
                if (!this.IsUplodType)
                {
                    this.stream.Dispose();
                    return "Only allowed to upload pictures.";
                }
                string returnName = base.Save();
                if (this.FileName != null)
                {
                    this.File.Save(this.FileName);
                    this.stream.Dispose();
                    return ImageUrl;
                }
                return null;
            }

            protected override string GetExtension()
            {
                if (this.File != null)
                {
                    string fileExtension = this.File.RawFormat.ToString().Substring(14),
                           jpgExtension = System.Drawing.Imaging.ImageFormat.Jpeg.Guid.ToString(),
                           gifExtension = System.Drawing.Imaging.ImageFormat.Gif.Guid.ToString(),
                           pngExtension = System.Drawing.Imaging.ImageFormat.Png.Guid.ToString(),
                           iconExtension = System.Drawing.Imaging.ImageFormat.Icon.Guid.ToString(),
                           bmpExtension = System.Drawing.Imaging.ImageFormat.Bmp.Guid.ToString(),
                           tiffExtension = System.Drawing.Imaging.ImageFormat.Tiff.Guid.ToString(),
                           wmfExtension = System.Drawing.Imaging.ImageFormat.Wmf.Guid.ToString(),
                           emfExtension = System.Drawing.Imaging.ImageFormat.Emf.Guid.ToString(),
                           exifExtension = System.Drawing.Imaging.ImageFormat.Exif.Guid.ToString();
                    fileExtension = fileExtension.Substring(0, fileExtension.Length - 1);
                    if (fileExtension == jpgExtension)
                    {
                        return ".jpg";
                    }
                    else if (fileExtension == gifExtension)
                    {
                        return ".gif";
                    }
                    else if (fileExtension == pngExtension)
                    {
                        return ".png";
                    }
                    else if (fileExtension == iconExtension)
                    {
                        return ".icon";
                    }
                    else if (fileExtension == bmpExtension)
                    {
                        return ".bmp";
                    }
                    else if (fileExtension == tiffExtension)
                    {
                        return ".tiff";
                    }
                    else if (fileExtension == wmfExtension)
                    {
                        return ".wmf";
                    }
                    else if (fileExtension == emfExtension)
                    {
                        return ".emf";
                    }
                    else if (fileExtension == exifExtension)
                    {
                        return ".exif";
                    }
                }
                return null;
            }
        }
    }
}

4.調用頁面,重點在這兒,官方用的是prettify.js的彈窗,我用的wbox.js的iframe加載MeiTuUpload.aspx頁面來實現的調用,官方封裝了個插件用於執行示例代碼來動態加載美圖秀秀插件,下面是代碼:
頁面代碼:

 <tr>
  <td class="bg1" height="25" align="right">縮略圖:</td>
  <td class="bg2"><img id="imgNewsInfo" src="<%=newsInfo.NewsInfoImage %>" width="220" height="200" />
 </td>
</tr>      
 <tr>
  <td class="bg1" height="25" align="right">縮略圖上傳:</td>
  <td class="bg2"><input type="hidden" id="filePath" name="filePath" value="<%=newsInfo.NewsInfoImage %>" /><a id="meitu" class="btngreen" href="javascript:;">拼圖</a> 
 </td>
</tr> 

js彈窗代碼:

var meitu = $("#meitu").wBox({ noTitle:true,title: "拼圖", requestType: "iframe", iframeWH: { width: 420, height: 400 }, target: "/NewsInfoManager/MeiTuUpload?InfoClass=2&newsInfoId=<%=newsInfo.NewsInfoID %>" });
//設置返回值的路var meitu = $("#meitu").wBox({ noTitle:true,title: "拼圖", requestType: "iframe", iframeWH: { width: 420, height: 400 }, target: "/NewsInfoManager/MeiTuUpload?InfoClass=2&newsInfoId=<%=newsInfo.NewsInfoID %>" });
//設置返回值的路徑
function setfilePath(data) {
    $('#filePath').val(data);
    $('#imgNewsInfo').attr('src',data);
}

function setfilePath(data) {
    $('#filePath').val(data);
    $('#imgNewsInfo').attr('src',data);
}

 博文地址:http://www.mikel.cn/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM