首页 > 其他分享 >图片上传生成缩略图相关code

图片上传生成缩略图相关code

时间:2023-08-18 15:56:00浏览次数:36  
标签:code MySqlParameter 缩略图 int System new 上传

记录一下以前的code(现在看起来当时的代码是这么写出来的,哈哈,自嘲一下),可以结合minio等obs文件服务器

    // 在ASP.NET中上传图片并生成缩略图
            //检查上传文件的格式是否有效 
            if (this.fileupload.PostedFile.ContentType.ToLower().IndexOf("image") < 0)
            {
                ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('上传图片格式无效')", true);
                return;
            }
            if (selectTime.Text.Trim().Length <= 0)
            {
                ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('请选择图片的分类日期')", true);
                return;
            }
            if (fileupload.HasFile)
            {
                string imgPath = "/StudentShow/StudentImgs/" + DateTime.Now.Year;
                string teximgTitleStr = Path.GetFileName(fileupload.PostedFile.FileName);//  图片title 类似:2D5A7274-2.jpg
                if (HaveUploadImg(teximgTitleStr))//去掉重复上传图片的方法
                {
                    ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('此张图片已经上传,\\r\\n\\n请不要重复操作哦!')", true);
                    return;
                }
                if (!Directory.Exists(Server.MapPath(imgPath)))
                {
                    Directory.CreateDirectory(Server.MapPath(imgPath));
                }
                string imgfileName = fileupload.PostedFile.FileName;
                string imgEx = imgfileName.Substring(imgfileName.LastIndexOf("."));

                if (imgEx.ToLower() != ".png" && imgEx.ToLower() != ".jpg" && imgEx.ToLower() != ".gif")
                {
                    ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('非法的图片格式')", true);
                    return;
                }

                float imgsize = ((float)(fileupload.PostedFile.ContentLength * 1.0) / 1024 / 1024);
                if (imgsize > 2.2)
                {
                    ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('上传的图片过大,最大建议2M以下,谢谢')", true);
                    return;
                }

                //生成原图 
                //    Byte[] oFileByte = new byte[this.fileupload.PostedFile.ContentLength];
                System.IO.Stream oStream = this.fileupload.PostedFile.InputStream;
                System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
                int oWidth = oImage.Width; //原图宽度 
                int oHeight = oImage.Height; //原图高度 
                int tWidth = 180; //设置缩略图初始宽度 
                int tHeight = 140; //设置缩略图初始高度 

                //按比例计算出缩略图的宽度和高度 
                if (oWidth >= oHeight)
                {
                    tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                }
                else
                {
                    tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                }
                //生成缩略原图 
                Bitmap tImage = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 
                g.Clear(Color.Transparent); //清空画布并以透明背景色填充 
                g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);

                string timeStrb = "b" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";//原图大图并为jpg的格式名称 //可以提出来
                string timeStrs = "s" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";//保存为小图并为jpg的格式名称
                // string imgPath = "/StudentShow/StudentImgs/" + DateTime.Now.Year;
                string oFullName = Server.MapPath(imgPath) + "/" + timeStrb; //保存原图的物理路径 
                string tFullName = Server.MapPath(imgPath) + "/" + timeStrs; //保存缩略图的物理路径 

                int  flagstr = GetImgCountByIsdel0();//获取img的flag,方便点击图片来回切换上下图片
                try
                {
                    //1 保存到数据库
                    string sqlstr = "insert into sumStudentImg(BimgPath,title,addTime,isDel,className,autoTime,SimgPath,flag) values(@BimgPath,@title,@addTime,@isDel,@className,@autoTime,@SimgPath,@flag)";
                    if (Mysqlhelper.ExecuterNoquery(sqlstr, System.Data.CommandType.Text, new MySqlParameter[]{
                        new MySqlParameter("@BimgPath", DateTime.Now.Year+"/"+timeStrb),
                        new MySqlParameter("@title",teximgTitleStr),//上传图片的名称
                        new MySqlParameter("@addTime",selectTime.Text),
                        new MySqlParameter("@isDel",'0'),
                        new MySqlParameter("@className",droplistClass.SelectedValue),
                        new MySqlParameter("@autoTime",DateTime.Now),
                        new MySqlParameter("@SimgPath", DateTime.Now.Year+"/"+timeStrs),
                        new MySqlParameter("@flag",flagstr)
                    }) > 0)
                    {
                        //2以JPG格式保存图片 
                        oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        // ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('恭喜上传成功ok')", true);
                        showUploadImgOk.Visible = true;
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(updatepanel, GetType(), "", "alert('图片上传出错,原因:" + ex.Message + "')", true);
                }
                finally
                {
                    //释放资源 
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }

 

标签:code,MySqlParameter,缩略图,int,System,new,上传
From: https://www.cnblogs.com/Fengge518/p/17640722.html

相关文章

  • [LeetCode][70]climbing-stairs
    ContentYouareclimbingastaircase.Ittakesnstepstoreachthetop.Eachtimeyoucaneitherclimb1or2steps.Inhowmanydistinctwayscanyouclimbtothetop? Example1:Input:n=2Output:2Explanation:Therearetwowaystoclimbtothet......
  • [LeetCode][62]unique-paths
    ContentThereisarobotonanmxngrid.Therobotisinitiallylocatedatthetop-leftcorner(i.e.,grid[0][0]).Therobottriestomovetothebottom-rightcorner(i.e.,grid[m-1][n-1]).Therobotcanonlymoveeitherdownorrightatanypointi......
  • [LeetCode][64]minimum-path-sum
    ContentGivenamxngridfilledwithnon-negativenumbers,findapathfromtoplefttobottomright,whichminimizesthesumofallnumbersalongitspath.Note:Youcanonlymoveeitherdownorrightatanypointintime. Example1:Input:grid=[[......
  • [LeetCode][55]jump-game
    ContentYouaregivenanintegerarraynums.Youareinitiallypositionedatthearray'sfirstindex,andeachelementinthearrayrepresentsyourmaximumjumplengthatthatposition.Returntrueifyoucanreachthelastindex,orfalseotherwise.......
  • [LeetCode][32]longest-valid-parentheses
    ContentGivenastringcontainingjustthecharacters'('and')',returnthelengthofthelongestvalid(well-formed)parenthesessubstring. Example1:Input:s="(()"Output:2Explanation:Thelongestvalidparentheses......
  • [LeetCode][53]maximum-subarray
    ContentGivenanintegerarraynums,findthesubarraywiththelargestsum,andreturnitssum. Example1:Input:nums=[-2,1,-3,4,-1,2,1,-5,4]Output:6Explanation:Thesubarray[4,-1,2,1]hasthelargestsum6.Example2:Input:nums=[1]Output:......
  • [LeetCode][10]regular-expression-matching
    ContentGivenaninputstrings andapatternp,implementregularexpressionmatchingwithsupportfor'.'and'*'where:'.'Matchesanysinglecharacter.​​​​'*'Matcheszeroormoreoftheprecedingelement.T......
  • [LeetCode][42]trapping-rain-water
    ContentGivennnon-negativeintegersrepresentinganelevationmapwherethewidthofeachbaris1,computehowmuchwateritcantrapafterraining. Example1:Input:height=[0,1,0,2,1,0,1,3,2,1,2,1]Output:6Explanation:Theaboveelevationmap......
  • LeetCode[64]MinimumPathSum
    ContentGivenamxngridfilledwithnon-negativenumbers,findapathfromtoplefttobottomright,whichminimizesthesumofallnumbersalongitspath.Note:Youcanonlymoveeitherdownorrightatanypointintime. Example1:Input:grid=[[......
  • LeetCode[55]JumpGame
    ContentYouaregivenanintegerarraynums.Youareinitiallypositionedatthearray'sfirstindex,andeachelementinthearrayrepresentsyourmaximumjumplengthatthatposition.Returntrueifyoucanreachthelastindex,orfalseotherwise.......