【譯】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, 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中。這是執行實際的調整大小。最后保存位圖和所有創建的對象的處置,以釋放資源。
另請參見
FileStream, Image, Bitmap, and Graphics

浙公網安備 33010602011771號