【译】MVC3 20个秘方-(12)改变图片的大小生成缩略图
问题
你允许用户上传一个图片,但是传统的来说,这个图片一般是从一个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, fil
补充:Web开发 , ASP.Net ,