【译】MVC3 20个秘方-(12)改变图片的大小生成缩略图

来源:未知 责任编辑:智问网络 发表时间:2013-09-26 23:49 点击:

 

问题

你允许用户上传一个图片,但是传统的来说,这个图片一般是从一个camera输出的,这个图片太大。所以你想展现一个简单的图片或者缩略图。在你的网站允许用户在他看到完整图片之前先预览缩略图(译者:这是一个很好的用户体验)。

解决方案

使用以下几个类去更新现有的文件上传功能去调整图片:FileStream, Image, Bitmap,和Graphics 类去指定宽度和高度。

讨论

在下面的例子,以前创建的FileUpload类将得到更新和重组。创建一个新的功能,称为ResizeImage执行调整图片大小。调整大小后的图像将被保存在以前的文件夹的子文件夹中,名为(thumbnail)缩略图。DeleteFile函数也被更新,同时删除缩略图和原始图像,并创建一个新的函数,并调用了两次删除功能

为了避免重复代码。下面是FileUpload类的代码:

译者:下边标红的代码是我加上去的。这样我们可以把图片和缩略图存到我们项目的文件夹下。否则他会存到:C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\目录下。

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Linq;

using System.Web;

using System.IO;

 

namespace MvcApplication.Utils

{

    public static class FileUpload

    {

        public static char DirSeparator = Path.DirectorySeparatorChar;

        public static string FilesPath = HttpContext.Current.Server.MapPath(string.Format("Content{0}Uploads{1}", DirSeparator, DirSeparator));

        public static string UploadFile(HttpPostedFileBase file)

        {

            // Check if we have a file

            if (null == file) return "";

            // Make sure the file has content

            if (!(file.ContentLength > 0)) return "";

            string fileName = file.FileName;

            string fileExt = Path.GetExtension(file.FileName);

            // Make sure we were able to determine a proper

            // extension

            if (null == fileExt) return "";

            // Check if the directory we are saving to exists

            if (!Directory.Exists(FilesPath))

            {

                // If it doesn't exist, create the directory

                Directory.CreateDirectory(FilesPath);

            }

            // Set our full path for saving

            string path = FilesPath + DirSeparator + fileName;

            // Save our file

            file.SaveAs(Path.GetFullPath(path));

            // Save our thumbnail as well

            ResizeImage(file, 150, 100);

            // Return the filename

            return fileName;

        }

        public static void DeleteFile(string fileName)

        {

            // Don't do anything if there is no name

            if (fileName.Length == 0) return;

            // Set our full path for deleting

            string path = FilesPath + DirSeparator + fileName;

            string thumbPath = FilesPath + DirSeparator +

            "Thumbnails" + DirSeparator + fileName;

            RemoveFile(path);

            RemoveFile(thumbPath);

        }

        private static void RemoveFile(string path)

        {

            // Check if our file exists

            if (File.Exists(Path.GetFullPath(path)))

            {

                // Delete our file

                File.Delete(Path.GetFullPath(path));

            }

        }

        public static void ResizeImage(HttpPostedFileBase file, int width, int height)

        {

 

            string thumbnailDirectory =

            String.Format(@"{0}{1}{2}", FilesPath,

            DirSeparator, "Thumbnails");

            // Check if the directory we are saving to exists

            if (!Directory.Exists(thumbnailDirectory))

            {

                // If it doesn't exist, create the directory

                Directory.CreateDirectory(thumbnailDirectory);

            }

            // Final path we will save our thumbnail

            string imagePath =

            String.Format(@"{0}{1}{2}", thumbnailDirectory,

            DirSeparator, file.FileName);

            // Create a stream to save the file to when we're

            // done resizing

            FileStream stream = new FileStream(Path.GetFullPath(

            imagePath), FileMode.OpenOrCreate);

            // Convert our uploaded file to an image

            Image OrigImage = Image.FromStream(file.InputStream);

            // Create a new bitmap with the size of our

            // thumbnail

            Bitmap TempBitmap = new Bitmap(width, height);

            // Create a new image that contains quality

            // information

            Graphics NewImage = Graphics.FromImage(TempBitmap);

            NewImage.CompositingQuality =

            CompositingQuality.HighQuality;

            NewImage.SmoothingMode =

            SmoothingMode.HighQuality;

            NewImage.InterpolationMode =

            InterpolationMode.HighQualityBicubic;

            // Create a rectangle and draw the image

            Rectangle imageRectangle = new Rectangle(0, 0,

            width, height);

            NewImage.DrawImage(OrigImage, imageRectangle);

            // Save the final file

            TempBitmap.Save(stream, OrigImage.RawFormat);

            // Clean up the resources

            NewImage.Dispose();

            TempBitmap.Dispose();

            OrigImage.Dispose();

            stream.Close();

            stream.Dispose();

        }

    }

}

 

上边的例子做了很多事,特别是在ResizeImage函数。

首先,如果缩略图目录不存在,它将被创建。接下来,一个新的FileStream会根据缩略图存放的完整路径被创建用于编辑。

原上传的图像根据uploaded的InputStream被转换为Image类的对象。一个新的位图会被根据图图像的宽度和高度创建。接下来用这个位图去创建一个新的Graphics对象。Graphics对象,NewImage,用于设置和定义质量,表面光滑,插补模式。如果没有这些设置,缩略图会不会好看非常像素化和调整笨拙。

一旦都设置好了,一个新的矩形被创建并且原始图像被画到Graphics中。这是执行实际的调整大小。最后保存位图和所有创建的对象的处置,以释放资源。

  另请参见

aspx">FileStream, Image, Bitmap, and Graphics

 


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

    推荐热点

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

    豫ICP备11007008号-1