zoukankan      html  css  js  c++  java
  • MVC3.0 上传图片并生成缩略图

    转自:http://mikelai.blog.163.com/blog/static/18411126620118771732675/

    Controller:
    public ActionResult Upload()
    {
    return View();
    }
    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
    var ostream = file.InputStream;
    var orimage = Image.FromStream(ostream);
    int owidth = orimage.Width; //原图宽度
    int oheight = orimage.Height; //原图高度
    int objwidth = 100; //设置缩略图初始宽度
    int objheight = 100; //设置缩略图初始高度
    //按比例计算出缩略图的宽度和高度
    if (owidth >= oheight)
    {
    objheight = (int)Math.Floor(Convert.ToDouble(oheight) * (Convert.ToDouble(objwidth) / Convert.ToDouble(owidth)));
    }
    else
    {
    objwidth = (int)Math.Floor(Convert.ToDouble(owidth) * (Convert.ToDouble(objheight) / Convert.ToDouble(oheight)));
    }
    Bitmap objimage = new Bitmap(objwidth, objheight);
    Graphics graphics = Graphics.FromImage(objimage);
    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
    graphics.Clear(Color.Transparent); //清空画布并以透明背景色填充
    graphics.DrawImage(orimage, new Rectangle(0, 0, objwidth, objheight), new Rectangle(0, 0, owidth, oheight), GraphicsUnit.Pixel);
     
    //rewrite imagename
    var extensionName = Path.GetExtension(file.FileName);
    var oriname = "ori" + DateTime.Now.ToString("yyyyMMddHHmmss") + extensionName;
    var objname = "obj" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
     
    var orifilePath = Path.Combine(HttpContext.Server.MapPath("/content/videos"), Path.GetFileName(oriname));
    var objfilePath= Path.Combine(HttpContext.Server.MapPath("/content/videos"), Path.GetFileName(objname));
    try
    {
    file.SaveAs(orifilePath);
    objimage.Save(objfilePath, System.Drawing.Imaging.ImageFormat.Png);
    }
     
    catch (Exception ex)
    {
    throw ex;
    }
    finally
    {
    //释放资源
    orimage.Dispose();
    graphics.Dispose();
    objimage.Dispose();
    }
     
    return RedirectToAction("Index");
    }
     
    View:
    @using (Html.BeginForm("Upload", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    <label>
    Filename:</label>
    <input type="file" name="file" />
    <input type="submit" value="Submit" />
    }
     
     
  • 相关阅读:
    今天在这里开博客,分享心情与技术
    tp3.2控制器返回时关闭子窗口刷新父页面
    关于iframe与$.load()哪个更好
    javascript的匿名函数的理解(转载学习)
    DOM入门学习笔记
    SQL学习基础笔记
    多线程和套接字入门学习笔记
    网络套接字学习以及聊天程序开发实例
    DOM 讲解结束
    JQuery 基础学习
  • 原文地址:https://www.cnblogs.com/heifengwll/p/3473276.html
Copyright © 2011-2022 走看看