webuploader批量上傳(轉)


webuploader插件單張上傳或批量上傳效果如下

HTML文件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="WebUploader.Demo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="css/smart-green.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="webuploader/webuploader.css" />  //webuplaoder樣式文件
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>  //先引用jquery插件
    <script type="text/javascript" src="webuploader/webuploader.min.js"></script>  //webuploader插件
    <script type="text/javascript" charset="utf-8" src="js/uploader.js"></script>  //JS動態圖片配置操作信息
    <style type="text/css">
        .fl { //相冊圖片ul li樣式向左浮動,JS文件uploader.js里動態添加 float: left;
            width: 350px;
            list-style-type: none;
        }

        .clear { //清除浮動
            clear: both;
        }
        
        .tab ul li {  //單張上傳格式排版樣式
            line-height: 30px;
            list-style-type: none;
        }

        .lef {
            float: left;
            width: 90px;
        }

        .rig {
            float: left;
            width: 870px;
        }
        
    </style>
</head>
<body>
    <form id="form1">
        <div class="smart-green tab">
            <h1>webuploader圖片單張,多張批量上傳,可設置生成縮略圖
            <span>運用webuploader無刷新上傳圖片</span>
            </h1>
            <ul style="height: 320px;">
                <li class="lef"><span>單張上傳:</span></li>
                <li class="rig">
                    <input type="text" style="float: left; height: 30px; width: 450px;" readonly="readonly" name="txtImgUrl" class="upload-path" />  //upload-path表示圖片上傳后返回的文件名帶目錄接受類
                    <div style="float: left; margin-left: 8px;" class="upload-box upload-img"></div> //引用upload-img動態JS添加一個按鈕
                    <div style="clear: both;"></div>
                    <img id="imageurl" class="upload-imgurl" width="300" />  //upload-imgurl表示上傳后返回接受類
                </li>
                <li class="clear"></li>
            </ul>
            <ul>
                <li class="lef"><span>批量上傳</span></li>
                <li class="rig">
                    <div style="float: left; " class="upload-box upload-album"></div>  //引用upload-album動態JS添加一個按鈕
                    <div style="float: left; margin-left: 8px;"><input id="chkThumb" name="chkThumb" type="checkbox" value="1" /><label for="chkThumb">是否生成縮略圖</label></div>
                    <div class="clear"></div>
                    <div class="photo-list">  //批量上傳后動態返回接收的photo-list類,內容寫在<ul>內
                        <ul>
                        <%--<li>
                        <input type="hidden" name="hid_photo_name" value="" />  //返回的隱藏input名為hid_photo_name,后台獲取將是一個數組
//單個值/Upload/20160625215133272.jpg|,帶縮略圖/Upload/20160625223245312.jpg|/Upload/thumb_20160625223245312.jpg <input type="hidden" name="hid_photo_remark" value="" /> //可以給圖片添加描述信息 <div class="img-box" onclick="setFocusImg(this);"> <img src="" bigsrc="" /> <span class="remark"><i>暫無描述...</i></span> </div> <a href="javascript:;" onclick="setRemark(this);">描述</a> //添加圖片描述 <a href="javascript:;" onclick="delImg(this);">刪除</a> //刪除圖片按鈕 </li>--%> </ul> </div> </li> <li class="clear"></li> </ul> <%--<label> <span>&nbsp;</span> <input type="button" class="button" value="Save" /> </label>--%> </div> </form> </body> <script type="text/javascript"> $(function () { //初始化上傳控件 $(".upload-img").InitUploader({ sendurl: "/ajax.ashx", }); $(".upload-album").InitUploader({ btntext: "批量上傳", multiple: true, water: false, thumbnail: false, sendurl: "/ajax.ashx", }); }); </script> </html>

以下是封裝好的uploader.js文件

$(function () {
    //初始化綁定默認的屬性
    $.upLoadDefaults = $.upLoadDefaults || {};
    $.upLoadDefaults.property = {
        multiple: false, //是否多文件
        water: false, //是否加水印
        thumbnail: false, //是否生成縮略圖
        sendurl: null, //發送地址
        filetypes: "jpg,jpge,png,gif", //文件類型
        filesize: "2048", //文件大小
        btntext: "瀏覽...", //上傳按鈕的文字
        swf: "/webuploader/uploader.swf" //SWF上傳控件相對地址,上傳SWF需要用到的文件
    };
    //初始化上傳控件
    $.fn.InitUploader = function (b) {
        var fun = function (parentObj) {
             var p = $.extend({}, $.upLoadDefaults.property, b || {});
            var btnObj = $('<div class="upload-btn">' + p.btntext + '</div>').appendTo(parentObj);
            //初始化屬性
            p.sendurl += "?action=UpLoadFile";
            if (p.water) {
                p.sendurl += "&IsWater=1";
            }
            if (p.thumbnail) {
                p.sendurl += "&IsThumbnail=1";
            }
            //if (!p.multiple) {
            //    p.sendurl += "&DelFilePath=" + parentObj.siblings(".upload-path").val();
            //}

            //初始化WebUploader
            var uploader = WebUploader.create({
                auto: true, //自動上傳
                swf: p.swf, //SWF路徑
                server: p.sendurl, //上傳地址
                pick: {
                    id: btnObj,
                    multiple: p.multiple
                },
                accept: {
                    /*title: 'Images',*/
                    extensions: p.filetypes
                    /*mimeTypes: 'image/*'*/
                },
                formData: {
                    'DelFilePath': '', //定義參數
                    url: '算定義參數'
                },
                fileVal: 'Filedata', //上傳域的名稱
                fileSingleSizeLimit: p.filesize * 1024 //文件大小
            });

            //當validate不通過時,會以派送錯誤事件的形式通知
            uploader.on('error', function (type) {
                switch (type) {
                    case 'Q_EXCEED_NUM_LIMIT':
                        alert("錯誤:上傳文件數量過多!");
                        break;
                    case 'Q_EXCEED_SIZE_LIMIT':
                        alert("錯誤:文件總大小超出限制!");
                        break;
                    case 'F_EXCEED_SIZE':
                        alert("錯誤:文件大小超出限制!");
                        break;
                    case 'Q_TYPE_DENIED':
                        alert("錯誤:禁止上傳該類型文件!");
                        break;
                    case 'F_DUPLICATE':
                        alert("錯誤:請勿重復上傳該文件!");
                        break;
                    default:
                        alert('錯誤代碼:' + type);
                        break;
                }
            });

            //當有文件添加進來的時候
            uploader.on('fileQueued', function (file) {
                //如果是單文件上傳,把舊的文件地址傳過去
                if (!p.multiple) {
                    uploader.options.formData.DelFilePath = parentObj.siblings(".upload-path").val(); 
                }
                //是否生成縮略圖
                if (!p.thumbnail) {                    
                    uploader.options.formData.thumbnail = $('#chkThumb').is(':checked');
                }
                //防止重復創建
                if (parentObj.children(".upload-progress").length == 0) {
                    //創建進度條
                    var fileProgressObj = $('<div class="upload-progress"></div>').appendTo(parentObj);
                    var progressText = $('<span class="txt">正在上傳,請稍候...</span>').appendTo(fileProgressObj);
                    var progressBar = $('<span class="bar"><b></b></span>').appendTo(fileProgressObj);
                    var progressCancel = $('<a class="close" title="取消上傳">關閉</a>').appendTo(fileProgressObj);
                    //綁定點擊事件
                    progressCancel.click(function () {
                        uploader.cancelFile(file);
                        fileProgressObj.remove();
                    });
                }
            });

            //文件上傳過程中創建進度條實時顯示
            uploader.on('uploadProgress', function (file, percentage) {
                var progressObj = parentObj.children(".upload-progress");
                progressObj.children(".txt").html(file.name);
                progressObj.find(".bar b").width(percentage * 100 + "%");
            });

            //當文件上傳出錯時觸發
            uploader.on('uploadError', function (file, reason) {
                uploader.removeFile(file); //從隊列中移除
                alert(file.name + "上傳失敗,錯誤代碼:" + reason);
            });

            //當文件上傳成功時觸發
            uploader.on('uploadSuccess', function (file, data) {             
                if (data.status == '0') {
                    var progressObj = parentObj.children(".upload-progress");
                    progressObj.children(".txt").html(data.msg);
                }
                if (data.status == '1') {
                    //如果是單文件上傳,則賦值相應的表單
                    if (!p.multiple) {
                        parentObj.siblings(".upload-name").val(data.name);                       
                        parentObj.siblings(".upload-size").val(data.size);
                        parentObj.siblings(".upload-imgurl").attr("src", data.path);
                        parentObj.siblings(".upload-path").val(data.path);
                    } else {
                        addImage(parentObj, data.path, data.thumb);
                    }
                    var progressObj = parentObj.children(".upload-progress");
                    progressObj.children(".txt").html("上傳成功:" + file.name);
                }
                uploader.removeFile(file); //從隊列中移除
            });

            //不管成功或者失敗,文件上傳完成時觸發
            uploader.on('uploadComplete', function (file) {
                var progressObj = parentObj.children(".upload-progress");
                progressObj.children(".txt").html("上傳完成");
                //如果隊列為空,則移除進度條
                if (uploader.getStats().queueNum == 0) {
                    progressObj.remove();
                }
            });
        };
        return $(this).each(function () {
            fun($(this));
        });
    }
});

/*圖片相冊處理事件
=====================================================*/
//添加圖片相冊
function addImage(targetObj, originalSrc, thumbSrc) {
    //插入到相冊UL里面
    var newLi = $('<li class="fl">'
    + '<img id="imagelist" class="imgage-list" width="300" src="' + originalSrc + '"/>'
    + '<input type="hidden" name="hid_photo_name" value="' + originalSrc + '|' + thumbSrc + '" />'
    + '<input type="hidden" name="hid_photo_remark" value="" />'
    //+ '<div class="img-box" onclick="setFocusImg(this);">'
    //+ '<img src="' + thumbSrc + '" bigsrc="' + originalSrc + '" />'
    //+ '<span class="remark"><i>暫無描述...</i></span>'
    //+ '</div>'
    //+ '<a href="javascript:;" onclick="setRemark(this);">描述</a>'
    + '<a href="javascript:;" onclick="delImg(this);">刪除</a>'
    + '</li>');
    newLi.appendTo(targetObj.siblings(".photo-list").children("ul"));

    //默認第一個為相冊封面
    var focusPhotoObj = targetObj.siblings(".focus-photo");
    if (focusPhotoObj.val() == "") {
        focusPhotoObj.val(thumbSrc);
        newLi.children(".img-box").addClass("selected");
    }
}
//設置相冊封面
function setFocusImg(obj) {
    var focusPhotoObj = $(obj).parents(".photo-list").siblings(".focus-photo");
    focusPhotoObj.val($(obj).children("img").eq(0).attr("src"));
    $(obj).parent().siblings().children(".img-box").removeClass("selected");
    $(obj).addClass("selected");
}
//設置圖片描述
function setRemark(obj) {
    var parentObj = $(obj); //父對象
    var hidRemarkObj = parentObj.prevAll("input[name='hid_photo_remark']").eq(0); //取得隱藏值
    var d = parent.dialog({
        title: "圖片描述",
        content: '<textarea id="ImageRemark" style="margin:10px 0;font-size:12px;padding:3px;color:#000;border:1px #d2d2d2 solid;vertical-align:middle;width:300px;height:50px;">' + hidRemarkObj.val() + '</textarea>',
        button: [{
            value: '批量描述',
            callback: function () {
                var remarkObj = $('#ImageRemark', parent.document);
                if (remarkObj.val() == "") {
                    parent.dialog({
                        title: '提示',
                        content: '親,總該寫點什么吧?',
                        okValue: '確定',
                        ok: function () { },
                        onclose: function(){
                            remarkObj.focus();
                        }
                    }).showModal();
                    return false;
                }
                parentObj.parent().parent().find("li input[name='hid_photo_remark']").val(remarkObj.val());
                parentObj.parent().parent().find("li .img-box .remark i").html(remarkObj.val());
            }
        }, {
            value: '單張描述',
            callback: function () {
                var remarkObj = $('#ImageRemark', parent.document);
                if (remarkObj.val() == "") {
                    parent.dialog({
                        title: '提示',
                        content: '親,總該寫點什么吧?',
                        okValue: '確定',
                        ok: function () { },
                        onclose: function () {
                            remarkObj.focus();
                        }
                    }).showModal();
                    return false;
                }
                hidRemarkObj.val(remarkObj.val());
                parentObj.siblings(".img-box").children(".remark").children("i").html(remarkObj.val());
            },
            autofocus: true
        }]
    }).showModal();
}
//刪除圖片LI節點
function delImg(obj) {
    var parentObj = $(obj).parent().parent();
    var focusPhotoObj = parentObj.parent().siblings(".focus-photo");
    var smallImg = $(obj).siblings(".img-box").children("img").attr("src");
    $(obj).parent().remove(); //刪除的LI節點
    //檢查是否為封面
    if (focusPhotoObj.val() == smallImg) {
        focusPhotoObj.val("");
        var firtImgBox = parentObj.find("li .img-box").eq(0); //取第一張做為封面
        firtImgBox.addClass("selected");
        focusPhotoObj.val(firtImgBox.children("img").attr("src")); //重新給封面的隱藏域賦值
    }
}
ajax.ashx文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace Project_Demo.Common
{
    /// <summary>
    /// _Ajax 的摘要說明
    /// </summary>
    public class _Ajax : IHttpHandler
    {
        string result = string.Empty;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string type = context.Request.QueryString["action"];
            switch (type)
            {
                case "UpLoadFile":
                    UploadImage(context);
                    break;                
                default:
                    //Uploader(context);
                    break;
            }
            context.Response.Write(result);
            context.Response.End();
        }
        private void UploadImage(HttpContext context)
        {            
            string isthumb = context.Request.Form["thumbnail"];
            bool thumb = isthumb == "true" ? true : false;
            //上傳圖片           
            HttpPostedFile postedFile = context.Request.Files[0];
            var path = "/Upload/";    //上傳保存的路徑
            int size = 2;    //文件大小限制,單位mb 
            ImageHelper up = new ImageHelper();
            //var upImage = up.UploadImage(postedFile, path, size, false);            
            //生成縮略圖
            var upImage = up.UploadImage(postedFile, path, size, thumb, 200);
            //生成水印
            //var upImage = up.UploadImage(postedFile, path, size, WatermarkType.Text, "水印文字", WatermarkPosition.Center, false);
            //生成水印+縮略圖
            //var upImage = up.UploadImage(postedFile, path, size, WatermarkType.Text, "水印文字", WatermarkPosition.Center, true, 200);
            result = JsonConvert.SerializeObject(upImage);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
ImageHelper.cs類
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

/// <summary>
/// 圖片通用上傳類
/// </summary>
public class ImageHelper
{
    protected UploadImageInfo upImage = new UploadImageInfo();
    /// <summary>
    /// 上傳圖片
    /// </summary>
    /// <param name="postedFile">文件</param>
    /// <param name="uploadPath">上傳文件夾路徑</param>
    ///<param name="maxSize">大小</param>
    /// <param name="thumbnail">是否生成縮略圖</param>
    public UploadImageInfo UploadImage(HttpPostedFile postedFile, string uploadPath, int maxSize, bool thumbnail, int width = 0, int height = 0)
    {
        //上傳配置
        //string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };  //文件允許格式
        //string[] fileTypes = { "image/png", "image/bmp", "image/gif", "image/jpeg" };        
        //string uploadpath = HttpContext.Current.Server.MapPath(pathbase);//獲取文件上傳路徑

        try
        {
            var filepath = HttpContext.Current.Server.MapPath(uploadPath);
            //目錄創建
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }

            //string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };  //文件允許格式
            string[] filetype = { "image/png", "image/bmp", "image/gif", "image/jpeg" };
            if (!filetype.Contains(postedFile.ContentType))
            {
                upImage.msg = "圖片格式錯誤";
            }
            int fileSize = postedFile.ContentLength;
            //大小驗證
            if (fileSize >= maxSize * 1024 * 1024)
            {
                upImage.msg = string.Format("圖片大小超出,請上傳小於{0}M的圖片", maxSize);
            }
            //保存圖片
            if (string.IsNullOrEmpty(upImage.msg))
            {
                var oldName = postedFile.FileName;
                //獲取文件擴展名稱
                string fileExt = Common.GetFileExt(oldName);
                //重命名文件        
                var newName = Common.Rename(oldName);
                //保存的路徑                
                postedFile.SaveAs(filepath + newName);
                //生成縮略圖
                if (thumbnail)
                {
                    string sFileName = "thumb_" + newName;//縮略圖文件名
                    this.MakeThumbnail(filepath + newName, filepath + sFileName, width, height, ThumbnailType.WidthHeightCut);
                    upImage.thumb = uploadPath + sFileName; //返回的小圖
                }

                upImage.status = (int)ResultCode.Success;
                upImage.msg = "上傳成功";
                upImage.name = oldName;
                upImage.path = uploadPath + newName; //返回的原圖片URL
                upImage.size = fileSize;
                upImage.extension = fileExt;
            }
            else
            {
                upImage.status = (int)ResultCode.Fail;
            }
        }
        catch
        {
            upImage.status = (int)ResultCode.Fail;
            upImage.msg = "圖片上傳出錯";
        }
        return upImage;
    }

    /// <summary>
    /// 上傳圖片加水印
    /// </summary>
    /// <param name="postedFile">文件</param>
    /// <param name="uploadPath">上傳文件夾路徑</param>
    /// <param name="maxSize">文件大小</param>
    /// <param name="waterType">水印類型</param>
    /// <param name="image_text">水印圖片&水印文字</param>
    /// <param name="position">水印位置</param>
    /// <param name="thumbnail">是否生成縮略圖</param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public UploadImageInfo UploadImage(HttpPostedFile postedFile, string uploadPath, int maxSize, WatermarkType waterType, string image_text, WatermarkPosition position, bool thumbnail, int width = 0, int height = 0)
    {
        try
        {
            var filepath = HttpContext.Current.Server.MapPath(uploadPath);
            //目錄創建
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }

            string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };  //文件允許格式
            if (filetype.Contains(postedFile.ContentType))
            {
                upImage.msg = "圖片格式錯誤";
            }
            int fileSize = postedFile.ContentLength;
            //大小驗證
            if (fileSize >= maxSize * 1024 * 1024)
            {
                upImage.msg = string.Format("圖片大小超出,請上傳小於{0}M的圖片", maxSize);
            }
            //保存圖片
            if (string.IsNullOrEmpty(upImage.msg))
            {
                var oldName = postedFile.FileName;
                //獲取文件擴展名稱
                string fileExt = Common.GetFileExt(oldName);
                //重命名文件        
                var newName = Common.Rename(oldName);
                //創建圖像流
                Image img = Image.FromStream(postedFile.InputStream);

                if (waterType == WatermarkType.Text)
                {
                    AddImageWaterMarkText(img, filepath + newName, image_text, (int)position, 90, "Verdana", 24);
                }
                else if (waterType == WatermarkType.Image)
                {
                    if (!File.Exists(image_text))
                    {
                        upImage.status = (int)ResultCode.Fail;
                        upImage.msg = "水印圖片不存在";
                        return upImage;
                    }
                    else
                    {
                        AddImageWaterMarkPic(img, filepath + newName, image_text, (int)position, 80, 10);
                    }
                }
                if (thumbnail)
                {
                    string sFileName = "thumb_" + newName;//縮略圖文件名
                    this.MakeThumbnail(filepath + newName, filepath + sFileName, width, height, ThumbnailType.WidthHeightCut);
                    upImage.thumb = uploadPath + sFileName; //返回的小圖
                }

                upImage.status = (int)ResultCode.Success;
                upImage.name = oldName;
                upImage.path = uploadPath + newName; //返回的原圖片URL
                upImage.size = fileSize;
                upImage.extension = fileExt;
            }
            else
            {
                upImage.status = (int)ResultCode.Fail;
            }
        }
        catch
        {
            upImage.status = (int)ResultCode.Fail;
            upImage.msg = "圖片上傳出錯";
        }
        return upImage;
    }

    /// <summary>
    /// 加圖片水印
    /// </summary>
    /// <param name="img">要加水印的原圖(System.Drawing)</param>
    /// <param name="filename">文件名</param>
    /// <param name="watermarkFilename">水印文件名</param>
    /// <param name="watermarkStatus">圖片水印位置1=左上 2=中上 3=右上 4=左中  5=中中 6=右中 7=左下 8=中下 9=右下</param>
    /// <param name="quality">加水印后的質量0~100,數字越大質量越高</param>
    /// <param name="watermarkTransparency">水印圖片的透明度1~10,數字越小越透明,10為不透明</param>    
    public static void AddImageWaterMarkPic(Image img, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
    {
        Graphics g = Graphics.FromImage(img);
        //設置高質量插值法
        //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        //設置高質量,低速度呈現平滑程度
        //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        Image watermark = new Bitmap(watermarkFilename);

        if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            return;

        ImageAttributes imageAttributes = new ImageAttributes();
        ColorMap colorMap = new ColorMap();

        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
        ColorMap[] remapTable = { colorMap };

        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

        float transparency = 0.5F;
        if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            transparency = (watermarkTransparency / 10.0F);


        float[][] colorMatrixElements = {
                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                            };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        int xpos = 0;
        int ypos = 0;

        switch (watermarkStatus)
        {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;
            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;
            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;
            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;
            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;
            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;
            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
        }

        g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
        ImageCodecInfo ici = null;
        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.MimeType.IndexOf("jpeg") > -1)
                ici = codec;
        }
        EncoderParameters encoderParams = new EncoderParameters();
        long[] qualityParam = new long[1];
        if (quality < 0 || quality > 100)
            quality = 80;

        qualityParam[0] = quality;

        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
        encoderParams.Param[0] = encoderParam;

        if (ici != null)
            img.Save(filename, ici, encoderParams);
        else
            img.Save(filename);

        g.Dispose();
        img.Dispose();
        watermark.Dispose();
        imageAttributes.Dispose();
    }

    /// <summary>
    /// 增加圖片文字水印
    /// </summary>
    /// <param name="img">要加水印的原圖(System.Drawing)</param>
    /// <param name="filename">文件名</param>
    /// <param name="watermarkText">水印文字</param>
    /// <param name="watermarkStatus">圖片水印位置1=左上 2=中上 3=右上 4=左中  5=中中 6=右中 7=左下 8=右中 9=右下</param>
    /// <param name="quality">加水印后的質量0~100,數字越大質量越高</param>
    /// <param name="fontname">水印的字體</param>
    /// <param name="fontsize">水印的字號</param>
    public static void AddImageWaterMarkText(Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
    {
        Graphics g = Graphics.FromImage(img);
        Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
        SizeF crSize;
        crSize = g.MeasureString(watermarkText, drawFont);

        float xpos = 0;
        float ypos = 0;

        switch (watermarkStatus)
        {
            case 1:
                xpos = (float)img.Width * (float).01;
                ypos = (float)img.Height * (float).01;
                break;
            case 2:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = (float)img.Height * (float).01;
                break;
            case 3:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = (float)img.Height * (float).01;
                break;
            case 4:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;
            case 5:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;
            case 6:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;
            case 7:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;
            case 8:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;
            case 9:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;
        }

        g.DrawString(watermarkText, drawFont, new SolidBrush(Color.LightGray), xpos + 1, ypos + 1);//文字陰影        

        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
        ImageCodecInfo ici = null;
        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.MimeType.IndexOf("jpeg") > -1)
                ici = codec;
        }
        EncoderParameters encoderParams = new EncoderParameters();
        long[] qualityParam = new long[1];
        if (quality < 0 || quality > 100)
            quality = 80;

        qualityParam[0] = quality;

        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
        encoderParams.Param[0] = encoderParam;

        if (ici != null)
            img.Save(filename, ici, encoderParams);
        else
            img.Save(filename);

        g.Dispose();
        img.Dispose();
    }

    /// <summary>
    /// 生成縮略圖
    /// </summary>
    /// <param name="originalImagePath">源圖路徑(物理路徑)</param>
    /// <param name="thumbnailPath">縮略圖路徑(物理路徑)</param>
    /// <param name="width">縮略圖寬度</param>
    /// <param name="height">縮略圖高度</param>
    /// <param name="mode">生成縮略圖的方式</param>
    protected void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumbnailType type)
    {
        Image originalImage = Image.FromFile(originalImagePath);
        int towidth = width;
        int toheight = height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;
        if (ow > oh)
        {
            type = ThumbnailType.Width;
        }
        else if (ow < oh)
        {
            type = ThumbnailType.Height;
        }
        switch (type)
        {
            case ThumbnailType.Width://指定寬,高按比例                    
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case ThumbnailType.Height://指定高,寬按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case ThumbnailType.WidthHeightCut://指定高寬裁減(不變形)                
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }

        //新建一個bmp圖片
        Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
        //新建一個畫板
        Graphics g = System.Drawing.Graphics.FromImage(bitmap);
        //設置高質量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        //設置高質量,低速度呈現平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //清空畫布並以透明背景色填充
        g.Clear(Color.Transparent);
        //在指定位置並且按指定大小繪制原圖片的指定部分
        g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
            new Rectangle(x, y, ow, oh),
            GraphicsUnit.Pixel);
        try
        {
            //以jpg格式保存縮略圖
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }

    #region 先上傳再加水印 (已注釋)
    ///// <summary>
    ///// 在圖片上增加文字水印
    ///// </summary>
    ///// <param name="Path">物理圖片路徑</param>
    ///// <param name="Path_sy">生成后帶文字水印的圖片路徑</param>
    ///// <param name="waterText">水印文字</param>
    //protected void AddWaterText(string path, string savePath, string waterText)
    //{
    //    System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    //    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
    //    g.DrawImage(image, 0, 0, image.Width, image.Height);
    //    System.Drawing.Font f = new System.Drawing.Font("Verdana", 18);
    //    System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.White);
    //    var x = image.Width * 0.4f;
    //    var y = image.Height * 0.5f;
    //    g.DrawString(waterText, f, b, x, y);
    //    g.Dispose();
    //    image.Save(savePath);
    //    image.Dispose();
    //}
    ///// <summary>
    ///// 在圖片上生成圖片水印
    ///// </summary>
    ///// <param name="Path">物理圖片路徑</param>
    ///// <param name="Path_syp">生成的帶圖片水印的圖片路徑</param>
    ///// <param name="Path_sypf">水印圖片路徑</param>
    //protected void AddWaterImage(string path, string savePath, string waterImage)
    //{
    //    System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    //    System.Drawing.Image copyImage = System.Drawing.Image.FromFile(waterImage);
    //    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
    //    g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width - 20, image.Height - copyImage.Height - 20, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
    //    g.Dispose();

    //    image.Save(savePath);
    //    image.Dispose();
    //}
    #endregion
}
UploadImageInfo.cs類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// 上傳圖片
/// </summary>
public class UploadImageInfo
{
    /// <summary>
    /// 狀態
    /// </summary>
    public int status
    {
        get { return _status; }
        set { _status = value; }
    }
    private int _status = 0;
    /// <summary>
    /// 圖片地址
    /// </summary>
    public string path
    {
        get { return _path; }
        set { _path = value; }
    }
    private string _path = string.Empty;

    /// <summary>
    /// 縮略圖地址
    /// </summary>
    public string thumb
    {
        get { return _thumb; }
        set { _thumb = value; }
    }
    private string _thumb = string.Empty;

    /// <summary>
    /// 文件名
    /// </summary>
    public string name
    {
        get { return _filename; }
        set { _filename = value; }
    }
    private string _filename = string.Empty;

    /// <summary>
    /// 文件大小
    /// </summary>    
    public int size
    {
        get { return _size; }
        set { _size = value; }
    }
    private int _size = 0;

    /// <summary>
    /// 消息
    /// </summary>
    public string msg
    {
        get { return _msg; }
        set { _msg = value; }
    }
    private string _msg = string.Empty;

    /// <summary>
    /// 擴展名
    /// </summary>
    public string extension
    {
        get { return _extension; }
        set { _extension = value; }
    }
    private string _extension = string.Empty;
}
Common.cs類文件獲取文件夾及擴展名
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

public class Common
{
    #region
    /// <summary>
    /// 重命名文件
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static string Rename(string fileName)
    {
        return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000) + Path.GetExtension(fileName);
    }

    /// <summary>
    /// 獲取文件名稱
    /// </summary>
    public static string GetFileExt(string fileName)
    {
        return Path.GetExtension(fileName);
    }
    #endregion
}

Enums.cs 類文件配置類型情況

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


/// <summary>
/// 圖片分類
/// </summary>
public enum ImageCategory
{
    /// <summary>
    ////// </summary>
    None = 0,
    /// <summary>
    /// banner
    /// </summary>
    Banner = 1,
    /// <summary>
    /// 新聞
    /// </summary>
    Article = 2,
    /// <summary>
    /// 商品
    /// </summary>
    Product = 3,
}

/// <summary>
/// 生成縮略圖類型
/// </summary>
public enum ThumbnailType
{
    /// <summary>
    /// 指定高寬縮放(可能變形)
    /// </summary>
    WidthHeight = 0,
    /// <summary>
    /// 指定寬,高按比例(不變形)
    /// </summary>
    Width = 1,
    /// <summary>
    /// 指定高,寬按比例(不變形)
    /// </summary>
    Height = 2,
    /// <summary>
    /// 指定高寬裁減(不變形)
    /// </summary>
    WidthHeightCut = 3,
    /// <summary>
    /// 指定高寬范圍(不變形)
    /// </summary>
    WidthHeightAuto = 4,
}

/// <summary>
/// 水印類型
/// </summary>
public enum WatermarkType
{
    /// <summary>
    /// 文字
    /// </summary>
    Text = 0,
    /// <summary>
    /// 圖片
    /// </summary>
    Image = 1
}

/// <summary>
/// 水印定位
/// </summary>
public enum WatermarkPosition
{
    /// <summary>
    /// 左上角
    /// </summary>
    TopLeft = 1,
    /// <summary>
    /// 中上
    /// </summary>
    TopCenter = 2,
    /// <summary>
    /// 右上角
    /// </summary>
    TopRight = 3,
    /// <summary>
    /// 左中
    /// </summary>
    CenterLeft = 4,
    /// <summary>
    /// 中心
    /// </summary>
    Center = 5,
    /// <summary>
    /// 右中
    /// </summary>
    CenterRigth = 6,
    /// <summary>
    /// 左下角
    /// </summary>
    BottomLeft = 7,
    /// <summary>
    /// 中下
    /// </summary>
    BottomCenter = 8,
    /// <summary>
    /// 右下角
    /// </summary>
    BottomRight = 9,
}
/// <summary>
/// 返回狀態
/// </summary>
public enum ResultCode
{
    /// <summary>
    /// 失敗0
    /// </summary>
    Fail = 0,
    /// <summary>
    /// 成功1
    /// </summary>
    Success = 1,


}

 


免責聲明!

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



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