图片预览剪裁上传

<!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 代码

时间: 2024-08-04 13:10:31

图片预览剪裁上传的相关文章

前端图片预览,上传前预览,兼容IE7、8、9、10、11,Firefox,Chrome

在现在的Web开发中不可避免的会做一个图片预览的功能, 比如在上传图片的情况下,一个很简单的办法就是讲图片上传至服务器之后,再将文件的URL返回回来,然后异步通过这个URL加载刚刚上传的图片,实现图片的预览, 很明显的在这个过程中两次Web请求,一次发送文件,一次下载文件,到最后这个文件如果在客户端被删除(取消上传,弃用这次的上传), 这整个过程都白费了.我们希望能够在图片上传之前就能进行图片的预览,这样就避免了不必要的网络请求和时间等待. 在IE中有如下方式 var url; var file

js实现图片预览以及上传

HTML 代码: <input  type="file" id="fileid" onchange="filesize(this)" runat="server" size="80" Width="200px" Height="25px"/>  <input  type="hidden" id="hidden_s&quo

利用jquery,html5实现图片预览实时上传

          html代码 <div class="form-group"> <label for="pic" class="col-md-1 control-label">小图:</label> <div class="col-md-4"> <input type="file" class="form-control" nam

小议头像预览裁剪上传的实现

在做头像上传的时候,浏览器默认是无法取得本地图片的,当然 HTML5 是可以的.不过IE6-8怎么破?目前比较通用的方案都是 flash 解决. 说道头像预览和裁剪,我最熟悉的就是 Discuz 的那个了,非常方便好用.不仅可以选择本地图片,还能直接调用摄像头拍摄,当然前提是你必须有个摄像头. 于是我心血来潮的想把他剥离出来给项目用,于是有就了此文..我就不说怎么提取怎么调用,就简单的谈谈他是怎么处理图片好了,反正不是我们想的那样,和我想的出入非常大. 这个插件呢,差不多分为四步处理:1. 前台

图片选择,预览及上传

记得以前老师教我们写项目,要实现图片上传的功能,我们都是先用一个input选好图片,然后单独做一个提交图片的按钮,点击按钮,使用form表单提交到后台,然后通过 // 获取上传的文件 HttpPostedFileBase file = Request.Files[0]; 这一行来获取上传到后台的文件,然后来验证上传的文件是不是图片,其实在前台,通过设置input属性,就可以限制我们只能选择图片文件了,当然,后台的验证也是不能少的, // 设置accept属性,限制能选择的文件类型为图片 <inp

如何预览将要上传的图片-使用H5的FileAPI

这篇将要说的东西已经不新鲜了. 参考资料: Reading files in JavaScript using the File APIs (鉴于作者在美国, 我姑且认为作者母语是英语, 当然链接中有本地化可以选择中文) 要做什么效果呢, 就是页面上有个<input type="file" />, 用户选择需要上传的图片后, 页面上显示将要上传的图片. 以前呢, 需要Ajax将原图上传到服务器, 得到成功响应后在页面上添加一张图片. 如果用户发现上传错了, 需要把服务器上的

前台页面 上传预览 调用上传服务

function openBrowse(){ var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false; if(ie){ document.getElementById("file").click(); document.getElementById("filename").value=document.getElementById("file"

js-jssdk微信H5选择多张图片预览并上传(兼容ios,安卓,已测试)

值得注意的是: 1.在微信H5中选择图片运用:wx.chooseImage,成功后返回:  res.localIds用于上传图片使用    上传图片:wx.uploadImage. 2.上传图片的时候务必是一张一张的上传的(建议采用递归) 3.一张图片上传成功后务必需要延迟个几百毫秒再执行下一张的上传. 案例:深圳艺星“#美力女生#星粉颜值夏令营,2019Yestar艺星整形” Html <div class="photos"> <p>同时选择上传1-9张照片,

H5图片预览、压缩、上传

目标实现: 1.选择图片, 前端预览效果 2.图片大于1.2M的时候, 对图片进行压缩 3.以表单的形式上传图片 4.图片删除 预览效果图: 代码说明: 1.input:file选择图片 <!-- html部分 --> <ul id="preview" class="clear"> <li class="fl"> <img src="/images/audition/icon_upload.pn