码迷,mamicode.com
首页 > Web开发 > 详细

图片预览剪裁上传

时间:2015-06-01 16:13:56      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
        #mask {
            float: left;
            width: 100%;
            z-index: 1000;
            display: inline;
            position: absolute;
            left: 0;
            height: 820px;
            background-color: #393939;
            overflow: hidden;
            top: 0;
            opacity: 0.4;
            filter: alpha(opacity=20);
            visibility: visible;
        }

        #dialog {
            float: left;
            width: 720px;
            z-index: 1001;
            display: inline;
            position: absolute;
            height: 720px;
            background-color: #ffffff;
            overflow: hidden;
            visibility:visible;
            left: 0px;
            top: 0px;
        }

        .model_header {
            padding: 15px;
            border-bottom: 1px solid #e5e5e5;
            min-height: 16.42857143px;
            display: block;
            font-size: 13px;
            color: #393939;
            line-height: 1.5;
            box-sizing: border-box;
        }

            .model_header .close {
                font-size: 32px;
                margin-top: -2px;
                padding: 0;
                cursor: pointer;
                background-color: transparent;
                border: 0;
                float: right;
                font-weight: bold;
                line-height: 1;
                color: #808080;
                text-shadow: 0 1px 0 #fff;
                opacity: 2;
                overflow: visible;
                margin: 0;
                box-sizing: border-box;
                align-items: flex-start;
                text-align: center;
            }

                .model_header .close:hover {
                    font-size: 32px;
                    margin-top: -2px;
                    padding: 0;
                    cursor: pointer;
                    background-color: transparent;
                    border: 0;
                    float: right;
                    font-weight: bold;
                    line-height: 1;
                    color: #000;
                    text-shadow: 0 1px 0 #fff;
                    opacity: 2;
                    overflow: visible;
                    margin: 0;
                    box-sizing: border-box;
                    align-items: flex-start;
                    text-align: center;
                }

            .model_header .blue {
                color: #478fca !important;
                font-size: 18px;
                margin: 10px 0 10px 0;
                line-height: 1.1;
                box-sizing: border-box;
                display: block;
            }

        .no_margin {
            margin: 0 !important;
            box-sizing: border-box;
            display: block;
            font-size: 13px;
            color: #393939;
            line-height: 1.5;
        }

            .no_margin .model_body {
                position: relative;
                padding: 20px;
                box-sizing: border-box;
                display: block;
                width: 100%;
                height: 570px;
            }

                .no_margin .model_body .file {
                    position: absolute;
                    display: none;
                }

                .no_margin .model_body .file_container {
                    position: relative;
                    height: auto;
                    border: 1px dashed #aaa;
                    border-radius: 4px;
                    text-align: center;
                    display: block;
                    top: 0;
                    left: 0;
                    right: 0;
                    background-color: #fff;
                    box-shadow: none;
                    transition: all 0.15s;
                    box-sizing: border-box;
                    color: #393939;
                    font-size: 20px;
                    line-height: 1.5;
                    display: inline-block;
                    cursor: pointer;
                    width: 100%;
                    height: 29px;
                }

                    .no_margin .model_body .file_container:hover {
                        position: relative;
                        height: auto;
                        border: 1px dashed #d88e08;
                        border-radius: 4px;
                        text-align: center;
                        display: block;
                        top: 0;
                        left: 0;
                        right: 0;
                        background-color: #fff;
                        box-shadow: none;
                        transition: all 0.15s;
                        box-sizing: border-box;
                        color: #393939;
                        line-height: 1.5;
                        display: inline-block;
                        cursor: pointer;
                        width: 100%;
                        height: 29px;
                    }

        .file_container .lab {
            cursor: pointer;
        }

        .no_margin .model_body .file_img {
            border-bottom-width: 0;
            margin-bottom: 1px;
            margin-top: 10px;
            position: relative;
            display:none;
            padding: 0;
            height: auto;
            width: 0 auto;
            max-width: 100%;
            margin: 0 4px;
            text-align: left;
            white-space: nowrap;
            overflow: hidden;
            line-height: 28px;
            vertical-align: top;
            box-sizing: border-box;
            cursor: pointer;
        }

        .no_margin .model_footer {
            text-align: center !important;
            padding-top: 12px;
            padding-bottom: 14px;
            border-top-color: #e4e9ee;
            box-shadow: none;
            background-color: #eff3f8;
            margin-top: 15px;
            padding: 19px 20px 20px;
            border-top: 1px solid #e5e5e5;
            box-sizing: border-box;
            display: block;
            font-size: 13px;
            color: #393939;
            line-height: 1.5;
            box-sizing: border-box;
        }

        .btn_sm {
            background-color: #87b87f !important;
            border-color: #87b87f;
            font-size: 13px;
            padding: 4px 9px;
            line-height: 1.39;
            display: inline-block;
            color: #FFF !important;
            text-shadow: 0 -1px 0 rgba(0,0,0,0.25) !important;
            background-image: none !important;
            border: 0;
            border-radius: 0;
            box-shadow: none !important;
            transition: all ease .15s;
            cursor: pointer;
            vertical-align: middle;
            margin: 0;
            position: relative;
            text-transform: none;
            overflow: visible;
            box-sizing: border-box;
            align-items: flex-start;
        }

        .selectstyle {
            width: 150px;
            margin-left: 7px;
        }
    </style>
    <link href="js/Jcrop/css/jquery.Jcrop.css" rel="stylesheet" />
    <script src="js/jquery.js"></script>
    <script src="js/Jcrop/js/jquery.Jcrop.js"></script>
</head>
<body>
    <div id="mask"></div>
    <div id="dialog">
        <div class="model_header">
            <input type="button" onclick="hide_dialog()" class="close" value="×" />
            <h4 class="blue">更 换 头 像</h4>
        </div>
        <div class="no_margin">
            <div class="model_body">
                <div id="choose" style="width: 75%; margin: 0 auto;">
                    <span class="file_container">
                        <label class="lab">
                            点击选择图片
                            <input type="file" id="uploadimg" class="file" />
                        </label>

                    </span>
                </div>
                <center>
                    <span class="file_img">
                        <img src="" width="500" height="400" alt="" id="TestImage" />
                    </span>
                </center>
            </div>
            <div class="model_footer">
                <form id="AvatarForm" action="">
                    <input type="hidden" id="x" name="x" />
                    <input type="hidden" id="y" name="y" />
                    <input type="hidden" id="w" name="w" />
                    <input type="hidden" id="h" name="h" />
                    <input type="button" id="BtnSaveAvatar" class="btn_sm" onclick="hide_dialog()" value="确 定" />
                    <input type="button" class="btn_sm" onclick="hide_dialog()" value="取 消" />
                </form>

            </div>
        </div>
    </div>
    <img src="" id="myimg"/>
</body>

</html>
<script type="text/javascript">

    var filetype = new Array(".gif", ".png", ".jpg", ".jpeg", ".bmp");
    jQuery(document).ready(function () {
        $("#uploadimg").change(function () {
            $("#choose").hide();

            $(".file_img").show();
            $("#TestImage").siblings().remove();
            previewimg();
        })
    })
    function editavatars() {
        if (document.getElementById(uploadimg).value.length < 1) {
            alert("请选择图片");
            return;
        }
        var file = document.getElementById(uploadimg).files[0];
        var extension = "." + file.name.split(.)[1];
        var result = $.inArray(extension, filetype);
        if (result == -1) {
            alert("只能是.gif, .png, .jpg, .jpeg, .bmp等格式的图片");
            return;
        }
        var formdata = new FormData();
        formdata.append("uploadimg", file);
        formdata.append("x", $("#x").val());
        formdata.append("y", $("#y").val());
        formdata.append("w", $("#w").val());
        formdata.append("h", $("#h").val());
        var xhr = null;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xhr != null) {
            xhr.open("post", "getDataHandler.ashx?action=uploandimg2");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    $("#myimg").attr("src", xhr.responseText);
                  
                }
            };
            xhr.send(formdata);
        }

    }
    function jiancai()
    {
        $("#TestImage").ready(function () {
            var api = jQuery.Jcrop("#TestImage", {
                bgColor: black,
                bgOpacity: .4,
                setSelect: [0, 0, 350, 400],  //设定4个角的初始位置
                aspectRatio: 1 / 1,
                onChange: updateCoords,
                onSelect: updateCoords,
                boxWidth: 700,
                boxHeight: 500,
                allowResize: false,
                allowSelect:false,
            })
        })
    }
    function previewimg(file) {
        var maxwidth = 500;
        var maxheight = 400;
        file = document.getElementById("uploadimg");
        if (file.files && file.files[0]) {
            var extension = "." + file.files[0].name.split(.)[1];
            var result = $.inArray(extension, filetype);
            if (result == -1) {
                alert("只能是.gif, .png, .jpg, .jpeg, .bmp等格式的图片");
                return;
            }
            //pre_img 为 预览 img标签的id
            var img = document.getElementById(TestImage);
            img.onload = function () {
                var rect = clacImgZoomParam(maxwidth, maxheight, img.offsetWidth, img.offsetHeight);
                img.width = rect.width;
                img.height = rect.height;
                img.style.marginLeft = rect.left + px;
                img.style.marginTop = rect.top + px;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                img.src = evt.target.result;
                jiancai();
            }
            reader.readAsDataURL(file.files[0]);
        }
    }
    function clacImgZoomParam(maxwidth, maxheight, width, height) {
        var param = { top: 0, left: 0, width: width, height: height };
        if (width > maxwidth || height > maxheight) {
            param.width = maxwidth;
            param.height = maxheight;
        }
        return param;
    }
    function hide_dialog() {
        document.getElementById("mask").style.visibility = "hidden";
        document.getElementById("dialog").style.visibility = "hidden";
        $("#TestImage").hide();
        $("#TestImage").siblings().remove();

    }
</script>
<script type="text/javascript">
    $(document).ready(function () {
        //$(‘#TestImage‘).Jcrop({
        //    onChange: updateCoords,
        //    onSelect: updateCoords
        //});
        $("#BtnSaveAvatar").click(function () {
            //var path = $("#TestImage").attr("src");
            //$.ajax({
            //    url: ‘getDataHandler.ashx?action=setimg‘,
            //    data: { ‘x‘: $("#x").val(), ‘y‘: $("#y").val(), ‘w‘: $("#w").val(), ‘h‘: $("#h").val(), "path": path },
            //    datatype: "text/json",
            //    type: ‘post‘,
            //    success: function (o) {
            //        $("#userimg").attr("src", o);
            //    }
            //});
            editavatars();
            return false;
        });
    });
    function updateCoords(c) {
        $(#x).val(c.x);
        $(#y).val(c.y);
        $(#w).val(c.w);
        $(#h).val(c.h);
    };
</script>
html代码
技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace mycssmodel
{
    /// <summary>
    /// getDataHandler 的摘要说明
    /// </summary>
    public class getDataHandler : IHttpHandler
    {
        string action;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            action = context.Request["action"];
             if (action.Equals("uploandimg2"))
            {
                HttpFileCollection img = context.Request.Files;
                string xstr = context.Request["x"];
                string ystr = context.Request["y"];
                string wstr = context.Request["w"];
                string hstr = context.Request["h"];
                var fileName = string.Empty;
                var path = "";
                var newFileName ="";
                for (int i = 0; i < img.Count; i++)
                {
                    using (var bitmap = GenerateThumbnail(500, 400, img[i].InputStream))
                    {
                        fileName = DateTime.Now.Ticks + ".jpg";
                        path = "/Jcrop/uploadImg/" + fileName;
                        newFileName = context.Server.MapPath("/Jcrop/uploadImg/" + fileName);
                        bitmap.Save(newFileName);
                        fileName = newFileName;
                    }
                }

                string savePath = "/Jcrop/uploadImg/" + Guid.NewGuid() + ".jpg";

                int x = 0;
                int y = 0;
                int w = 1;
                int h = 1;
                try
                {
                    x = int.Parse(xstr);
                    y = int.Parse(ystr);
                    w = int.Parse(wstr);
                    h = int.Parse(hstr);
                }
                catch { }

                ImageCut ic = new ImageCut(x, y, w, h);
                System.Drawing.Bitmap cuted = ic.KiCut(new System.Drawing.Bitmap(newFileName));
                string cutPath = context.Server.MapPath(savePath);
                cuted.Save(cutPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                context.Response.Write(savePath);
            }
        }

        private System.Drawing.Bitmap GenerateThumbnail(int maxWidth, int maxHeight, System.IO.Stream imgFileStream)
        {
            using (var img = System.Drawing.Image.FromStream(imgFileStream))
            {
                var sourceWidth = img.Width;
                var sourceHeight = img.Height;
                var thumbWidth = sourceWidth; //要生成的图片的宽度  
                var thumbHeight = sourceHeight; //要生成图片的的高度  

                //计算生成图片的高度和宽度  
                if (sourceWidth > maxWidth || sourceHeight > maxHeight)
                {
                    var rateWidth = (double)sourceWidth / maxWidth;
                    var rateHeight = (double)sourceHeight / maxHeight;

                    if (rateWidth > rateHeight)
                    {
                        thumbWidth = maxWidth;
                        thumbHeight = (int)Math.Round(sourceHeight / rateWidth);
                    }
                    else
                    {
                        thumbWidth = (int)Math.Round(sourceWidth / rateHeight);
                        thumbHeight = maxHeight;
                    }
                }

                var bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight);
                //从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。  
                using (var gr = System.Drawing.Graphics.FromImage(bmp))
                {
                    //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality  
                    gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    //下面这个也设成高质量  
                    gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    //下面这个设成High  
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    //把原始图像绘制成上面所设置宽高的缩小图  
                    var rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
                    gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight,
                                 System.Drawing.GraphicsUnit.Pixel);
                    return bmp;
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
一般处理程序ashx 代码

 

图片预览剪裁上传

标签:

原文地址:http://www.cnblogs.com/yuanyue/p/4544132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!