zoukankan      html  css  js  c++  java
  • [原创]ASP.NET MVC调用美图秀秀开放平台拼图实现

    [原创]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: { 420, height: 400 }, target: "/NewsInfoManager/MeiTuUpload?InfoClass=2&newsInfoId=<%=newsInfo.NewsInfoID %>" });
    //设置返回值的路var meitu = $("#meitu").wBox({ noTitle:true,title: "拼图", requestType: "iframe", iframeWH: { 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/


    作者:mikel 
    出处:http://www.cnblogs.com/mikel/ 
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 
    该文章也同时发布在我的独立博客中-www.mikel.cn

     
    分类: 开发手记
  • 相关阅读:
    点击cell后 cell的背景不变,cell上的字体颜色发生改变的功能实现
    各种属性设置
    多列表 ,菜单
    正则表达式
    多个storyboard之间的跳转问题
    关于uicollectionview的个人学习
    uiscrollview的自动布局
    手动自动布局
    关于简单的跳转问题
    深入理解@class和#import的区别
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2881612.html
Copyright © 2011-2022 走看看