zoukankan      html  css  js  c++  java
  • ASP.NET MVC中使用uploadify上传图片并按照规定大小压缩图片

     $(document).ready(function () {         
                $('#uploadify').uploadify({
                    onUploadSuccess: function (file, returndata, response) {
                        var data = eval('(' + returndata + ')');
                        if (response == true && data.Success == 'true') {
                            $("input[name=BACKIMG]").attr("value", data.FileName);//data.FileName为图片保存路径
                            $('#mainForm').submit();
                        } else {
                            alert(data.Message);
                        }
                    },
                    'height': 20,
                    'width': 35,
                    'uploadLimit': 1,
                    'queueSizeLimit': 1,
                    'queueID': 'fileQueue',              
                    'removeCompleted': false,
                    'auto': false,
                    'multi': false,
                    'buttonText': '浏览图片',
                    'swf': '@Url.Content("~/Scripts/uploadify/uploadify.swf")',
                    'uploader': '@Url.Content("~/Scripts/uploadify/UploadAttach.ashx")'
                });

    将图片上传到服务器的方法为UploadAttach.ashx

     /// <summary>
        /// UploadAttach 的摘要说明
        /// </summary>
        public class UploadAttach : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                HttpPostedFile fileData = context.Request.Files["fileData"];
                string floder = context.Request["floder"];
                if (fileData != null)
                {
                    try
                    {
                        // 文件上传后的保存路径
                        string path = "~/img/";                  
                        string filePath = context.Server.MapPath(path);
                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }
                        string saveFileName = Guid.NewGuid().ToString() + fileData.FileName;
                    
                        string newFilePath = filePath + saveFileName;
                        fileData.SaveAs(newFilePath);
    
                        //图片裁切
                        var thumbFilePath = newFilePath.Replace(Path.GetExtension(newFilePath),
                                                                ".thumb" + Path.GetExtension(newFilePath));
                        ImageKit.MakeCenterThumbnail(newFilePath, thumbFilePath, 1602, 400);
                        if (File.Exists(newFilePath))
                        {
                            File.Delete(newFilePath);
                        }
                        context.Response.Write("{'Success':'true','FileName':'" + saveFileName.Replace(".", ".thumb.") + "'}");
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write("{'Success':'false','Message':'"+ex.Message+"'}");
                    }
                }
                else
                {
                    context.Response.Write("{'Success':'false','Message':'请选择要上传的文件'}");
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }

    图片裁剪压缩的方法

     public static class ImageKit
        {
              public static bool MakeCenterThumbnail(string origPath, string destPath, int width, int height)
            {
                try
                {
                    using (Image image = Image.FromFile(origPath))
                    {
                        int originalWidth = image.Width;
                        int originalHeight = image.Height;
                        double ratio = Math.Max((originalWidth / (double)width < originalHeight / (double)height)
                                            ? originalWidth / (double)width
                                            : originalHeight / (double)height, 1);
    
                        var cutSize = new Size((int)Math.Round(width * ratio, 0), (int)Math.Round(height * ratio, 0));
    
                        int x = (int)Math.Round((double)(originalWidth - cutSize.Width) / 2, 0);
                        int y = (int)Math.Round((double)(originalHeight - cutSize.Height) / 2, 0); ;
    
                        var bitmap = new Bitmap(width, height);
                        using (var graphics = Graphics.FromImage(bitmap))
                        {
                            graphics.CompositingQuality = CompositingQuality.HighQuality;
                            graphics.SmoothingMode = SmoothingMode.HighQuality;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.Clear(Color.White);
    
                            var destRect = new Rectangle(0, 0, width, height);
                            var originalRect = new Rectangle(x, y, cutSize.Width, cutSize.Height);
                            graphics.DrawImage(image, destRect, originalRect, GraphicsUnit.Pixel);
                        }
                        #region wjy20131004修改
                        // 以下代码为保存图片时,设置压缩质量
                        EncoderParameters encoderParams = new EncoderParameters();
                        long[] quality = new long[1];
                        quality[0] = 100;
                        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                        encoderParams.Param[0] = encoderParam;
                        //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
                        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo jpegICI = null;
                        for (int i = 0;i < arrayICI.Length;i++)
                        {
                            if (arrayICI[i].FormatDescription.Equals("JPEG"))
                            {
                                jpegICI = arrayICI[i];
                                //设置JPEG编码
                                break;
                            }
                        }
                        if (jpegICI != null)
                        {
                            bitmap.Save(destPath, jpegICI, encoderParams);
                        }
    
                        //bitmap.Save(destPath);
                        #endregion
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

    使用方法:

    1,首先要添加JS引用

    <script src="../../Scripts/uploadify/v3.1/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
    <link href="../../Scripts/uploadify/v3.1/uploadify1.css" rel="stylesheet" type="text/css" />

    2,在页面中显示上传附件的按钮:

    <div id="fileQueue">
    </div>
    <input type="file" name="uploadify" id="uploadify" />
    <input type="hidden" name="BACKIMG" value=""/>

    注意:隐藏控件BACKIMG是上传文件的路径,文件上传成功后要给它赋值,这样在表单提交成功后才可以根据图片路径读取到上传图片

    3,如下所示Form表单   

    <form id="mainForm" method="post" action='@Url.Action(Model.Action)'> </form>

      提交时调用上传图片的方法

     function submitbut() {
                var filecount = $('#fileQueue').find('div').length;
                if (filecount > 0) {
                    $('#uploadify').uploadify('upload', '*');
                } else {
                    $('#mainForm').submit();
                }
            }
  • 相关阅读:
    在Vue构建的SPA网页里 刷新的话,显示404页面
    springboot2.x 设置404页面
    关于Typora不显示PicGo.app的问题
    DBeaver中table插入新的数据
    DBeaver修改table的column名字
    Zeal
    Android Studio 快速创建 Toast
    使用VSCode调试单个JavaScript文件
    使用maven打包普通的java项目
    在命令行界面实现彩色字符输出 -- 并且介绍和这个相关的比较好用的java类库
  • 原文地址:https://www.cnblogs.com/lihfeiblogs/p/4120590.html
Copyright © 2011-2022 走看看