web 上传图片以及裁减

37 篇文章 0 订阅
16 篇文章 0 订阅

1、上传图片以及图片的裁减

jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传、取消、删除,上传前缩略图预览、列表显示图片大小,支持上传进度条显示;支持各种动态语言开发的服务器端

在完成图片的上传以后,我们有时需要对图片进行裁减以满足需要,Jcrop是一个可以让用户来裁减图片的的插件。

代码如下:

<!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>
    <title></title>
    <script src="scripts/jquery2.0.2.js" type="text/javascript"></script>
    <!--上传图片-->
    <script src="scripts/fileupload/jquery-ui-1.10.2.custom.js" type="text/javascript"></script>
    <script src="scripts/fileupload/jquery.fileupload.js" type="text/javascript"></script>
    <script src="scripts/fileupload/jquery.iframe-transport.js" type="text/javascript"></script>
    <!--裁剪图片-->
    <script type="text/javascript" src="scripts/Jcrop/jquery.Jcrop.js"></script>
    <script type="text/javascript" src="scripts/Jcrop/jquery.color.js"></script>
    <link rel="stylesheet" type="text/css" href="scripts/Jcrop/jquery.Jcrop.css" />
    <script type="text/javascript">
        var imagecrop;
        var ToFix = function (value, precision) {
            var power = Math.pow(10, precision || 0);
            return String(Math.round(value * power) / power);
        };
        //记录选择的的坐标
        var showCoords = function (c) {
            var position = "";
            position += "x=" + ToFix(c.x, 0) + "&y=" + ToFix(c.y, 0);
            position += "&x2=" + ToFix(c.x2, 0) + "&y2=" + ToFix(c.y2, 0);
            position += "&w=" + ToFix(c.w, 0) + "&h=" + ToFix(c.h, 0);
            $("#coords").val(position);
        };
        //裁剪图片
        var ImageCrop = function (dom) {
            var url = $(dom).parent().attr("value");
            var coords = $("#coords").val();
            var cut_flag = $.trim(coords) == "" ? false : true;
            $.post("imagecut.aspx?" + coords, { url: url, flag: cut_flag }, function (text) {
                eval("var obj = " + text);
                if (obj.success == "true") {
                    imagecrop.destroy();
                    $("#preview").html("");
                    var html = "";
                    html += "<div  url=" + obj.url + " style=\"float:left;width:120px;height:200px;\">";
                    html += "<img src='" + obj.url + "' width='120' height='160'/>";
                    html += "<input type=\"button\" style=\"background-image: url(images/delete.png); border: 0px solid rgb(255, 255, 255); padding: 0px; width: 67px; height: 26px;margin-left:26px;margin-top:14px; cursor: pointer;\" οnclick=\"this.parentNode.parentNode.removeChild(this.parentNode);\" /></div>";
                    $("#imageUploaded").append(html);
                } else {
                    alert("操作失败,请重试!");
                    return false;
                }
            }, "text");
        };
        //上传图片
        var uploadImage = function () {
            $("#uploadBtnId").fileupload({
                url: "upload.aspx",
                autoUpload: true,
                forceIframeTransport: true,    // 兼容ie7
                done: function (e, data) {//添加成功以后执行的函数
                    var str = $('pre', data.result).text() || data.result.text();
                    str = str.replace(/\\+/i, '/');
                    if (str != null && $.trim(str) != "") {
                        var result = JSON.parse(str);
                        if (result.success) {
                            var html = "";
                            for (var i = 0; i < result.list.length; i++) {
                                var file = result.list[i];
                                html += "<div style=\"float:left\" value=" + file.url + ">";
                                html += "<img id=\"uploadimagecrop\" src='" + file.url + "'/><input type=\"button\" style=\"background-image: url(images/save.png); border: 0px solid rgb(255, 255, 255); padding: 0px; width: 67px; height: 26px; cursor: pointer;\" οnclick=\"ImageCrop(this);return false;\" />";
                                html += "</div>";
                            }
                            $("#preview").html(html);

                            $("#uploadimagecrop").Jcrop({
                                onChange: showCoords,
                                onSelect: showCoords
                                //aspectRatio: 2 / 3 //宽高比aspectRatio:1 宽高比例是1:1

                            }, function () {
                                imagecrop = this;
                            });
                        } else {
                            alert("上传图片失败");
                        }

                    }
                }
            }).on('fileuploadadd', function (e, data) {

                //判断文件大小
                var sizemark = true;
                for (var i in data.files) {
                    if (data.files[i].size > 5120000) {
                        sizemark = false;
                        break;
                    }
                }
                if (!sizemark) {
                    alert("当个文件大小不能超过5M");
                    return false;
                }
                //判断文件数量
                var files = data.files;
                if (files.length > 1) {
                    alert("每次请上传一张图片,剪裁后完成添加。");
                    return false;
                }

                var reg = new RegExp("(\.|\/)(jpe?g|png)$", "i");
                for (var i = 0; i < files.length; i++) {
                    var result = reg.test(files[i].name);
                    if (!result) {
                        alert("请上传jpg,jpeg,png格式的图片!");
                         return false;
                    }
                }

                // 清空裁剪的坐标
                $("#coords").val("");

            }).on('fileuploadprocessalways', function (e, data) {

            }).on('fileuploadprogressall', function (e, data) {
                //var progress = parseInt(data.loaded / data.total * 100, 10);
                //$('#progress .progress-bar').append("<p>" + progress + "</p>");
                //$('#progress .progress-bar').css('width', progress + '%');

            }).on('fileuploaddone', function (e, data) {

            }).on('fileuploadfail', function (e, data) {

            });
        };
        $(function () {
            uploadImage();
        });
    </script>
</head>
<body>
    <input type="hidden" id="coords" />
    <input id="uploadBtnId" type="file" name="files[]" multiple="" accept="image/png, image/jpg, image/jpeg" />
    <div id="preview" class="preview">
    </div>
    <div id="imageUploaded" class="imgUploaded">
    </div>
    <div class="clear">
    </div>
    <em style="color: red; margin-left: 180px;">照片文件大小应小于5MB</em>
    <br />
    <br />
</body>
</html>
上传图片类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace ImageUploadCrop
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                HttpPostedFile file = Request.Files["files[]"];
                string path = Server.MapPath("~/images/temp/");
                //当前待上传的服务端路径 
                String newName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                String newFileName = newName + "_" + System.IO.Path.GetFileName(file.FileName);
                string imageUrl = path + newFileName;
                file.SaveAs(imageUrl);
                sb.Append("{\"success\":\"true\",\"list\":[");
                sb.Append("{\"url\":\"images/temp/" + newFileName + "\"}");
                sb.Append("]}");
            }
            catch (Exception ex)
            {
                sb.Append("{\"success\":\"false\"}");
            }
            
            Response.Write(sb.ToString());
            Response.End();
        }
    }
}

裁减图片类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace ImageUploadCrop
{
    public partial class imagecut : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String json = "{";
            try
            {
                string url = Request["url"];
                int width;
                int height;
                bool flag = Convert.ToBoolean(Request["flag"]);//如果为真,则进行的裁剪
                string filename = url.Substring(url.LastIndexOf("/") + 1, url.LastIndexOf(".") - url.LastIndexOf("/") - 1);
                string suffix = url.Substring(url.LastIndexOf("."));
                if (flag)
                {
                    int x = Convert.ToInt32(Request["x"]);
                    int y = Convert.ToInt32(Request["y"]);
                    int w = Convert.ToInt32(Request["w"]);
                    int h = Convert.ToInt32(Request["h"]);
                    Bitmap b = new Bitmap(Server.MapPath(url));
                    width = w;
                    height = h;
                    Bitmap bmpOut = new Bitmap(w, h, PixelFormat.Format24bppRgb);
                    //System.Drawing.Image bmpOut = new Bitmap(w, h);
                    Graphics g = Graphics.FromImage(bmpOut);
                    g.DrawImage(b, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
                    g.Dispose();
                    string virtual_path  = "images/product/" + filename + "_crop" + suffix;;
                    //string path = Server.MapPath("~/images/product/");
                    //string actual_path = path + filename + "_crop" + suffix;
                    string actual_path = Server.MapPath(virtual_path);
                    bmpOut.Save(actual_path);
                    bmpOut.Dispose();
                    b.Dispose();
                    
                    if (File.Exists(Server.MapPath(url)))
                    {
                        try
                        {
                            File.Delete(Server.MapPath(url));
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    url = virtual_path;
                }
                else
                {
                    System.Drawing.Image initImage = System.Drawing.Image.FromFile(Server.MapPath(url));
                    width = initImage.Width;
                    height = initImage.Height;
                    initImage.Dispose();
                    string source_path = Server.MapPath(url);
                    string dest_path = Server.MapPath("~/images/product/"+filename+suffix);
                    File.Copy(source_path, dest_path);
                    File.Delete(source_path);
                }
                json += "\"success\":\"true\", \"url\":\"" + url + "\", \"height\":\"" + height + "\",\"width\":\"" + width + "\"";
                json += "}";
            }
            catch (Exception ex)
            {
                json += "\"success\":\"false\"";
                json += "}";
            }
            Response.Write(json.ToString());
            Response.End();
        }
    }
}



Demo下载地址:http://download.csdn.net/detail/u011872945/7290681


参考网站如下:

jQuery File Upload :http://blueimp.github.io/jQuery-File-Upload/


JCrop官网:deepliquid.com/content/Jcrop.html

Jcrop插件说明:www.zhangxinxu.com/wordpress/?p=359

实现裁减的时候可以实现图片的旋转,可以参考网站:www.zhangxinxu.com/wordpress/?p=804

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值