zoukankan      html  css  js  c++  java
  • asp.net上传图片并生成等比例缩略图(.Net自带函数完成)

      /**//// <summary>
            /// 图片上传,带上缩略图
        /// </summary>
            /// <param name="FileUpload1">上传的控件的ID</param>
            /// <param name="SavePath">保存的路径,相对路径如“/Images/Picture/”,使用配置文件</param>
            /// <param name="refName">返回的文件名,不带路径</param>
            /// <param name="width">缩略图的宽</param>
            /// <param name="height">缩略图的高</param>
            /// <param name="maxLength">图片最大的大小</param>
            /// <returns></returns>
            public bool UpLoadImage(HtmlInputFile FileUpload1, string SavePath, ref string refName, int width, int height, int maxLength)
            {
                //在转换的时候需求使用系统路径
                SavePath = "~" + SavePath;
                /**////成功状态
                bool ret = true;
                /**////上传文件名称组
                string fileNames = string.Empty;
                //上传文件总大小
                int fileLength = 0;
                //图片类型
                string imgType = string.Empty;
                //图片类型集合
                ICollection ic = new string[] { ".gif", ".jpg", ".GIF", ".JPG" };
                ArrayList imgTypes = new ArrayList(ic);

                /**////判断上传文件的有效性

                ///检查文件扩展名字
                string name = System.IO.Path.GetFileName(FileUpload1.Value);
                if (name == "")
                {
                    /**////状态信息
                    ret = false;
                    refName = "图片不存在";
                    return false;
                }
                imgType = System.IO.Path.GetExtension(FileUpload1.Value);
                if (!imgTypes.Contains(imgType))
                {
                    /**////状态信息
                    ret = false;
                    refName = "图片格式不对";
                    return false;
                }
                fileLength = fileLength + FileUpload1.PostedFile.ContentLength;

                //系统规定大小
                int sysLength = maxLength * 1024;
                if (fileLength > sysLength)
                {
                    /**////状态信息
                    ret = false;
                    refName = "图片超过200KB上限!";
                     return false;
                }
                /**////图片上传
                try
                {
                    string picPath = SavePath;

                    string fileName, fileExtension;
                    /**////上传文件的文件名
                    fileName = System.IO.Path.GetFileName(FileUpload1.Value);
                    if (fileName != "")
                    {
                        /**////上传文件的扩展名
                        fileExtension = System.IO.Path.GetExtension(fileName);
                        /**////生成新的文件名
                        fileName = DateTime.Now.ToString("yyyyMMddHHmmffff") + fileExtension;
                        /**////可根据扩展名字的不同保存到不同的文件夹
                        string date = DateTime.Now.ToString("yyyyMM");
                        picPath = Server.MapPath(picPath + date + "/");
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(picPath);
                        if (!di.Exists)
                        {
                            di.Create();
                        }
                        /**////注意:可能要修改您的文件夹的匿名写入权限。
                        FileUpload1.PostedFile.SaveAs(picPath + fileName);
                        refName = date + "/" + fileName;
                        GetThumbnailImage(SavePath , date + "/", fileName, width, height);
                    }

                }
                catch
                {

                    ret = false;
                    refName = "上传失败!";
                    return false;
                }
                return ret;
            }

    生成缩略图代码:

    /**//// <param name="SavePath">原始路径</param>
            /// <param name="pathDate">添加的月份路径</param>
            /// <param name="picFilePath">保存的文件名</param>
            /// <param name="width">宽</param>
            /// <param name="height">高</param>
            public void GetThumbnailImage(string SavePath, string pathDate,string picFilePath, int width, int height)
            {
                //添加small100的前缀大小
           //程序内相对的服务器路径小图片
          string strRelativeSmallPath = SavePath + CommEnum.Pictures_Small100 + pathDate;

                string SmallPath100 = Server.MapPath(strRelativeSmallPath + picFilePath);
                string machpath = Server.MapPath(SavePath + pathDate + picFilePath);
                string isDir = SmallPath100.Substring(0, SmallPath100.LastIndexOf('\'));
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(isDir);
                if (!di.Exists)
                {
                    di.Create();
                }
                Bitmap img = new Bitmap(machpath); //read picture to memory

                int h = img.Height;
                int w = img.Width;
                int ss, os;// source side and objective side
                double temp1, temp2;
                //compute the picture's proportion
                temp1 = (h * 1.0D) / height;
                temp2 = (w * 1.0D) / width;
                if (temp1 < temp2)
                {
                    ss = w;
                    os = width;
                }
                else
                {
                    ss = h;
                    os = height;
                }

                double per = (os * 1.0D) / ss;
                if (per < 1.0D)
                {
                    h = (int)(h * per);
                    w = (int)(w * per);
                }
                // create the thumbnail image
                System.Drawing.Image imag2 = img.GetThumbnailImage(w, h,
                     new System.Drawing.Image.GetThumbnailImageAbort(ImageAbort),
                     IntPtr.Zero);
                Bitmap tempBitmap = new Bitmap(w, h);
                System.Drawing.Image tempImg = System.Drawing.Image.FromHbitmap(tempBitmap.GetHbitmap());
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(tempImg);
                g.Clear(Color.White);

                int x, y;

                x = (tempImg.Width - imag2.Width) / 2;
                y = (tempImg.Height - imag2.Height) / 2;

                g.DrawImage(imag2, x, y, imag2.Width, imag2.Height);

                try
                {
                    if (img != null)
                        img.Dispose();
                    if (imag2 != null)
                        imag2.Dispose();
                    if (tempBitmap != null)
                        tempBitmap.Dispose();

                    string fileExtension = System.IO.Path.GetExtension(machpath).ToLower();
                    //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.
                    switch (fileExtension)
                    {
                        case ".gif": tempImg.Save(SmallPath100, ImageFormat.Gif); break;
                        case ".jpg": tempImg.Save(SmallPath100, ImageFormat.Jpeg); break;
                        case ".bmp": tempImg.Save(SmallPath100, ImageFormat.Bmp); break;
                        case ".png": tempImg.Save(SmallPath100, ImageFormat.Png); break;
                    }                               
                }
                catch
                {
                    throw new Exception("图片上传失败");
                }
                finally
                {
                    //释放内存
                    if (tempImg != null)
                        tempImg.Dispose();
                    if (g != null)
                        g.Dispose();
                }
            }

    附:Image.GetThumbnailImage方法:

    一 般来说,使用GetThumbnailImage生成图片缩略图其实效果还是可以的,一般上传jpg格式效果也不错,但是有时候就会出现问题。比如“如当 源图尺寸过大时,生成的缩略图质量会很低”,还有“当源图是一个Gif图片且含有透明色时,生成的缩略图会将透明色填充成黑色”,如果“在缩略图较大时效 果也不好,尤其是超过120”通过MSDN来看:

    Image.GetThumbnailImage 方法
    返回此 Image 对象的缩略图。

    [Visual Basic]Public Function GetThumbnailImage( _   ByVal thumbWidth As Integer, _   ByVal thumbHeight As Integer, _   ByVal callback As Image.GetThumbnailImageAbort, _   ByVal callbackData As IntPtr _) As Image[C#]public Image GetThumbnailImage(   int thumbWidth,   int thumbHeight,   Image.GetThumbnailImageAbort callback,   IntPtr callbackData);[C++]public: Image* GetThumbnailImage(   int thumbWidth,   int thumbHeight,   Image.GetThumbnailImageAbort* callback,   IntPtr callbackData);[JScript]public function GetThumbnailImage(   thumbWidth : int,   thumbHeight : int,   callback : Image.GetThumbnailImageAbort,   callbackData : IntPtr) : Image;
    参数
    thumbWidth
    请求的缩略图的宽度(以像素为单位)。
    thumbHeight
    请求的缩略图的高度(以像素为单位)。
    callback
    一个 Image.GetThumbnailImageAbort 委托。在 GDI+ 1.0 版中不使用此委托。即便如此,也必须创建一个委托并在该参数中传递对此委托的引用。
    callbackData
    必须是 IntPtr.Zero。
    返回值
    用于表示该缩略图的 Image 对象。

    备注
    如果 Image 对象包含一个嵌入式缩略图像,则此方法会检索嵌入式缩略图,并将其缩放为所需大小。如果 Image 对象不包含嵌入式缩略图像,此方法会通过缩放主图像创建一个缩略图像。

    当 所请求的缩略图大小约为 120×120 时,GetThumbnailImage 工作正常。如果从一个有嵌入式缩略图的 Image 对象中请求一个较大的缩略图像(比如 300×300),则在缩略图像的质量会有显著的降低。通过调用 DrawImage 缩放主图像(而非嵌入式缩略图),则效果可能较好。

    示例
    [C#] 下面的示例创建并显示一个缩略图图像。从不调用此委托。

    [C#] public bool ThumbnailCallback(){return false;}public void Example_GetThumb(PaintEventArgs e){Image.GetThumbnailImageAbort myCallback =new Image.GetThumbnailImageAbort(ThumbnailCallback);Bitmap myBitmap = new Bitmap("Climber.jpg");Image myThumbnail = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero);e.Graphics.DrawImage(myThumbnail, 150, 75);}      

    此文章为转载的

  • 相关阅读:
    vue路由传参页面刷新参数丢失问题解决方案
    理解MVC,MVP 和 MVVM
    HTTPS用的是对称加密还是非对称加密?
    元素显示隐藏的9种思路
    CSS中层叠上下文
    DOM盒模型和位置 client offset scroll 和滚动的关系
    css重点知识和bug解决方法
    你可能不知道的CSS
    如何在 React 中优雅的写 CSS?
    html5不常用标签应用场景
  • 原文地址:https://www.cnblogs.com/weiying/p/weiying_10_22.html
Copyright © 2011-2022 走看看