不经保存,直接生成上传图片的等比例的高质量缩略图

来源:未知 责任编辑:智问网络 发表时间:2013-11-10 20:23 点击:

 

我们可以使用FileUpload.FileBytes属性直接得到上传文件的字节数组,从而可以直接生成上传文件的缩略图。代码如下:

 

ASPX 代码

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

 

  protected void Button1_Click(object sender, EventArgs e)

  {

    String fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);

    System.Drawing.Image image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(FileUpload1.FileBytes));

    int newWidth = 300, newHeight = 200;

    if ((decimal)image.Width / image.Height > (decimal)newWidth / newHeight)

    {

      newHeight =Convert.ToInt32((decimal)image.Height * newWidth / image.Width);

    }

    else if ((decimal)image.Width / image.Height < (decimal)newWidth / newHeight)

    {

      newWidth = Convert.ToInt32((decimal)image.Width * newHeight / image.Height);     

    }

    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newWidth, newHeight);

    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);

    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

    System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);

    g.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);

    bmp.Save(Server.MapPath("~/") + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt);

    bmp.Dispose();

    image.Dispose();

  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title>不经保存,直接生成上传图片的等比例的高质量缩略图</title>

</head>

<body>

  <form id="form1" runat="server">

  <asp:FileUpload ID="FileUpload1" runat="server" />

  <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="上传并生成缩略图" />

  </form>

</body>

</html>

    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • 浅析.NET下XML数据访问新机制
    • asp.net 面试+笔试题目第1/2页
    • C# 邮件地址是否合法的验证
    • asp.net 设置GridView的选中行的实现代码
    • C#高级编程:数据库连接[1]
    • 经典C++程序1
    • IIS 自动回收导致后台定时器失效的问题解决
    • ASP.NET&#160;GridView列表代码示例
    • Asp.net MVC源码分析--Action Filter的链式调用
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1