C#.Net 上傳圖片,限制圖片大小,檢查類型完整版
源代碼:
處理圖片類,如檢查圖片大小,按寬度比例縮小圖片
public
class
CImageLibrary
{
public enum ValidateImageResult { OK, InvalidFileSize, InvalidImageSize }
//檢查圖片大小
public static ValidateImageResult ValidateImage( string file, int MAX_FILE_SIZE, int MAX_WIDTH, intMAX_HEIGHT)
{
byte[] bs = File.ReadAllBytes(file);
double size = (bs.Length / 1024);
//大於50KB
if (size > MAX_FILE_SIZE) return ValidateImageResult.InvalidFileSize;
Image img = Image.FromFile(file);
if (img.Width > MAX_WIDTH || img.Height > MAX_HEIGHT) returnValidateImageResult.InvalidImageSize;
return ValidateImageResult.OK;
}
//按寬度比例縮小圖片
public static Image GetOutputSizeImage(Image imgSource, int MAX_WIDTH)
{
Image imgOutput = imgSource;
Size size = new Size(imgSource.Width, imgSource.Height);
if (imgSource.Width <= 3 || imgSource.Height <= 3) return imgSource; //3X3大小的圖片不轉換
if (imgSource.Width > MAX_WIDTH || imgSource.Height > MAX_WIDTH)
{
double rate = MAX_WIDTH / ( double)imgSource.Width;
if (imgSource.Height * rate > MAX_WIDTH)
rate = MAX_WIDTH / ( double)imgSource.Height;
size.Width = Convert.ToInt32(imgSource.Width * rate);
size.Height = Convert.ToInt32(imgSource.Height * rate);
imgOutput = imgSource.GetThumbnailImage(size.Width, size.Height, null, IntPtr.Zero);
}
return imgOutput;
}
//按比例縮小圖片
public static Image GetOutputSizeImage(Image imgSource, Size outSize)
{
Image imgOutput = imgSource.GetThumbnailImage(outSize.Width, outSize.Height, null, IntPtr.Zero);
return imgOutput;
}
public static byte[] GetImageBytes( string imageFileName)
{
Image img = Image.FromFile(imageFileName);
return GetImageBytes(img);
}
public static byte[] GetImageBytes(Image img)
{
if (img == null) return null;
try
{
System.IO.MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
byte[] bs = ms.ToArray();
ms.Close();
return bs;
}
catch { return null; }
}
public static Image FromBytes( byte[] bs)
{
if (bs == null) return null;
try
{
MemoryStream ms = new MemoryStream(bs);
Image returnImage = Image.FromStream(ms);
ms.Close();
return returnImage;
}
catch { return null; }
}
}
{
public enum ValidateImageResult { OK, InvalidFileSize, InvalidImageSize }
//檢查圖片大小
public static ValidateImageResult ValidateImage( string file, int MAX_FILE_SIZE, int MAX_WIDTH, intMAX_HEIGHT)
{
byte[] bs = File.ReadAllBytes(file);
double size = (bs.Length / 1024);
//大於50KB
if (size > MAX_FILE_SIZE) return ValidateImageResult.InvalidFileSize;
Image img = Image.FromFile(file);
if (img.Width > MAX_WIDTH || img.Height > MAX_HEIGHT) returnValidateImageResult.InvalidImageSize;
return ValidateImageResult.OK;
}
//按寬度比例縮小圖片
public static Image GetOutputSizeImage(Image imgSource, int MAX_WIDTH)
{
Image imgOutput = imgSource;
Size size = new Size(imgSource.Width, imgSource.Height);
if (imgSource.Width <= 3 || imgSource.Height <= 3) return imgSource; //3X3大小的圖片不轉換
if (imgSource.Width > MAX_WIDTH || imgSource.Height > MAX_WIDTH)
{
double rate = MAX_WIDTH / ( double)imgSource.Width;
if (imgSource.Height * rate > MAX_WIDTH)
rate = MAX_WIDTH / ( double)imgSource.Height;
size.Width = Convert.ToInt32(imgSource.Width * rate);
size.Height = Convert.ToInt32(imgSource.Height * rate);
imgOutput = imgSource.GetThumbnailImage(size.Width, size.Height, null, IntPtr.Zero);
}
return imgOutput;
}
//按比例縮小圖片
public static Image GetOutputSizeImage(Image imgSource, Size outSize)
{
Image imgOutput = imgSource.GetThumbnailImage(outSize.Width, outSize.Height, null, IntPtr.Zero);
return imgOutput;
}
public static byte[] GetImageBytes( string imageFileName)
{
Image img = Image.FromFile(imageFileName);
return GetImageBytes(img);
}
public static byte[] GetImageBytes(Image img)
{
if (img == null) return null;
try
{
System.IO.MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
byte[] bs = ms.ToArray();
ms.Close();
return bs;
}
catch { return null; }
}
public static Image FromBytes( byte[] bs)
{
if (bs == null) return null;
try
{
MemoryStream ms = new MemoryStream(bs);
Image returnImage = Image.FromStream(ms);
ms.Close();
return returnImage;
}
catch { return null; }
}
}
上傳文件自定義類. 業務邏輯全部在CFileUpload類!
public
class
CFileUpload
{
private FileUpload _fileUpload;
private string _savePath;
private string _LastUploadedFile = string.Empty;
private bool _AutoGenFileName = false;
public string LastUploadedFile { get { return _LastUploadedFile; } }
private string PICTURE_FILE = "[.gif.png.jpeg.jpg.bmp]";
private string ZIP_FILE = "[.zip.rar]";
private string MUILT_MEDIA_FILE = "[.mpeg.mpg.fla.exe.wma]";
private int IMG_MAX_WIDTH = 0; //未指定寬度
private int IMG_MAX_HEIGHT = 0; //未指定高度
/// <summary>
/// 構造器
/// </summary>
/// <param name="fileUpload">Asp.net FileUpload對象</param>
/// <param name="savePath">保存目錄,不包含文件名</param>
/// <param name="autoGenFileName">自動生成文件名</param>
public CFileUpload(FileUpload fileUpload, string savePath, bool autoGenFileName)
{
_savePath = savePath;
_fileUpload = fileUpload;
_AutoGenFileName = autoGenFileName;
}
/// <summary>
/// 構造器
/// </summary>
/// <param name="fileUpload">Asp.net FileUpload對象</param>
/// <param name="savePath">保存目錄,不包含文件名</param>
public CFileUpload(FileUpload fileUpload, string savePath)
{
_savePath = savePath;
_fileUpload = fileUpload;
}
/// <summary>
/// 上傳RAR文件
/// </summary>
public bool UploadRARFile()
{
return DoUpload(ZIP_FILE);
}
/// <summary>
/// 上傳視頻文件
/// </summary>
public bool UploadVideo()
{
return DoUpload(MUILT_MEDIA_FILE);
}
/// <summary>
/// 上傳圖片文件
/// </summary>
public bool UploadImage()
{
return DoUpload(PICTURE_FILE);
}
public bool UploadImage( int maxWidth, int maxHeight)
{
this.IMG_MAX_WIDTH = maxWidth;
this.IMG_MAX_HEIGHT = maxHeight;
return DoUpload(PICTURE_FILE);
}
/// <summary>
/// 上傳任何支持的文件
/// </summary>
public bool UploadAnySupported()
{
return DoUpload(PICTURE_FILE + ZIP_FILE + MUILT_MEDIA_FILE);
}
/// <summary>
/// 生成新的文件名
/// </summary>
private string GetNewFileName( string folder, string fileName)
{
//_AutoGenFileName==true 或者文件名長度>50,自動生成32位GUID文件名
if (_AutoGenFileName || StrUtils.GetStringLength(fileName) >= 50)
{
string ext = System.IO.Path.GetExtension(fileName);
string newfile = Guid.NewGuid().ToString().Replace("-", "") + ext;
return folder + newfile;
}
else
{
if (System.IO.File.Exists(folder + fileName))
{
string ext = System.IO.Path.GetExtension(fileName);
string filebody = fileName.Replace(ext, "");
int x = 1;
while ( true) //如果文件存在,生成尾部帶(x)的文件
{
string newfile = folder + filebody + "(" + x.ToString() + ")" + ext;
if (!System.IO.File.Exists(newfile))
return folder + filebody + "(" + x.ToString() + ")" + ext;
else
x++;
}
}
else
return folder + fileName;
}
}
/// <summary>
/// 最大支持小於1MB的文件。
/// </summary>
private bool AllowMaxSize( int fileLength)
{
int MAX_SIZE_UPLOAD = 1024; //最大支持上傳小於1MB的文件。
double kb = fileLength / 1024;
return ( int)kb < MAX_SIZE_UPLOAD;
}
private bool DoUpload( string allowedExtensions)
{
bool fileOK = false;
if (!_fileUpload.HasFile) return false; //上傳控件中如果不包含文件,退出
// 得到文件的后綴
string fileExtension = System.IO.Path.GetExtension(_fileUpload.FileName).ToLower();
// 看包含的文件是否是被允許的文件后綴
fileOK = allowedExtensions.IndexOf(fileExtension) > 0;
//檢查上傳文件大小
fileOK = fileOK & AllowMaxSize(_fileUpload.FileBytes.Length);
if (!fileOK) return false; //如檢查不通過,退出
try
{
// 文件另存在服務器指定目錄下
string savefile = GetNewFileName(_savePath, _fileUpload.FileName);
if (IsUploadImage(fileExtension))//保存圖片
{
System.Drawing.Image output = CImageLibrary.FromBytes(_fileUpload.FileBytes);
// 檢查圖片寬度/高度/大小
if ( this.IMG_MAX_WIDTH != 0 && output.Width > this.IMG_MAX_WIDTH)
{
output = CImageLibrary.GetOutputSizeImage(output, this.IMG_MAX_WIDTH);
}
Bitmap bmp = new Bitmap(output);
bmp.Save(savefile, output.RawFormat);
}
else//其它任何文件
{
_fileUpload.PostedFile.SaveAs(savefile);
}
_LastUploadedFile = savefile;
return true;
}
catch
{
return false;
}
}
private bool IsUploadImage( string fileExtension)
{
bool isImage = PICTURE_FILE.IndexOf(fileExtension) > 0;
return isImage;
}
}
{
private FileUpload _fileUpload;
private string _savePath;
private string _LastUploadedFile = string.Empty;
private bool _AutoGenFileName = false;
public string LastUploadedFile { get { return _LastUploadedFile; } }
private string PICTURE_FILE = "[.gif.png.jpeg.jpg.bmp]";
private string ZIP_FILE = "[.zip.rar]";
private string MUILT_MEDIA_FILE = "[.mpeg.mpg.fla.exe.wma]";
private int IMG_MAX_WIDTH = 0; //未指定寬度
private int IMG_MAX_HEIGHT = 0; //未指定高度
/// <summary>
/// 構造器
/// </summary>
/// <param name="fileUpload">Asp.net FileUpload對象</param>
/// <param name="savePath">保存目錄,不包含文件名</param>
/// <param name="autoGenFileName">自動生成文件名</param>
public CFileUpload(FileUpload fileUpload, string savePath, bool autoGenFileName)
{
_savePath = savePath;
_fileUpload = fileUpload;
_AutoGenFileName = autoGenFileName;
}
/// <summary>
/// 構造器
/// </summary>
/// <param name="fileUpload">Asp.net FileUpload對象</param>
/// <param name="savePath">保存目錄,不包含文件名</param>
public CFileUpload(FileUpload fileUpload, string savePath)
{
_savePath = savePath;
_fileUpload = fileUpload;
}
/// <summary>
/// 上傳RAR文件
/// </summary>
public bool UploadRARFile()
{
return DoUpload(ZIP_FILE);
}
/// <summary>
/// 上傳視頻文件
/// </summary>
public bool UploadVideo()
{
return DoUpload(MUILT_MEDIA_FILE);
}
/// <summary>
/// 上傳圖片文件
/// </summary>
public bool UploadImage()
{
return DoUpload(PICTURE_FILE);
}
public bool UploadImage( int maxWidth, int maxHeight)
{
this.IMG_MAX_WIDTH = maxWidth;
this.IMG_MAX_HEIGHT = maxHeight;
return DoUpload(PICTURE_FILE);
}
/// <summary>
/// 上傳任何支持的文件
/// </summary>
public bool UploadAnySupported()
{
return DoUpload(PICTURE_FILE + ZIP_FILE + MUILT_MEDIA_FILE);
}
/// <summary>
/// 生成新的文件名
/// </summary>
private string GetNewFileName( string folder, string fileName)
{
//_AutoGenFileName==true 或者文件名長度>50,自動生成32位GUID文件名
if (_AutoGenFileName || StrUtils.GetStringLength(fileName) >= 50)
{
string ext = System.IO.Path.GetExtension(fileName);
string newfile = Guid.NewGuid().ToString().Replace("-", "") + ext;
return folder + newfile;
}
else
{
if (System.IO.File.Exists(folder + fileName))
{
string ext = System.IO.Path.GetExtension(fileName);
string filebody = fileName.Replace(ext, "");
int x = 1;
while ( true) //如果文件存在,生成尾部帶(x)的文件
{
string newfile = folder + filebody + "(" + x.ToString() + ")" + ext;
if (!System.IO.File.Exists(newfile))
return folder + filebody + "(" + x.ToString() + ")" + ext;
else
x++;
}
}
else
return folder + fileName;
}
}
/// <summary>
/// 最大支持小於1MB的文件。
/// </summary>
private bool AllowMaxSize( int fileLength)
{
int MAX_SIZE_UPLOAD = 1024; //最大支持上傳小於1MB的文件。
double kb = fileLength / 1024;
return ( int)kb < MAX_SIZE_UPLOAD;
}
private bool DoUpload( string allowedExtensions)
{
bool fileOK = false;
if (!_fileUpload.HasFile) return false; //上傳控件中如果不包含文件,退出
// 得到文件的后綴
string fileExtension = System.IO.Path.GetExtension(_fileUpload.FileName).ToLower();
// 看包含的文件是否是被允許的文件后綴
fileOK = allowedExtensions.IndexOf(fileExtension) > 0;
//檢查上傳文件大小
fileOK = fileOK & AllowMaxSize(_fileUpload.FileBytes.Length);
if (!fileOK) return false; //如檢查不通過,退出
try
{
// 文件另存在服務器指定目錄下
string savefile = GetNewFileName(_savePath, _fileUpload.FileName);
if (IsUploadImage(fileExtension))//保存圖片
{
System.Drawing.Image output = CImageLibrary.FromBytes(_fileUpload.FileBytes);
// 檢查圖片寬度/高度/大小
if ( this.IMG_MAX_WIDTH != 0 && output.Width > this.IMG_MAX_WIDTH)
{
output = CImageLibrary.GetOutputSizeImage(output, this.IMG_MAX_WIDTH);
}
Bitmap bmp = new Bitmap(output);
bmp.Save(savefile, output.RawFormat);
}
else//其它任何文件
{
_fileUpload.PostedFile.SaveAs(savefile);
}
_LastUploadedFile = savefile;
return true;
}
catch
{
return false;
}
}
private bool IsUploadImage( string fileExtension)
{
bool isImage = PICTURE_FILE.IndexOf(fileExtension) > 0;
return isImage;
}
}
使用說明:
頁面的Button.Click事件
protected
void
btnUploadImg_Click(
object
sender, EventArgs e)
{
try
{
if (!FileUploadImg.HasFile) return;
string virtualFilePath = "~//" + CAppConfiguration.Current.BbsUploadFilePath;
string savePath = this.Server.MapPath(virtualFilePath); //保存文件物理路徑
//調用CFileUpload類
CFileUpload upload = new CFileUpload(FileUploadImg, savePath, false);
//上傳圖片文件
bool ret = upload.UploadImage();
if (ret)
{
string filename = System.IO.Path.GetFileName(upload.LastUploadedFile);
string imgHTML = "<img alt=''''貼圖圖片'''' src=''''{0}'''' />";
this.hfLastUploadImage.Value = filename;
string root = CGlobals.GetHttpRoot( this);
imgHTML = string.Format(imgHTML, root + "/" + CAppConfiguration.Current.BbsUploadFilePath + filename);
FreeTextBox1.Text = FreeTextBox1.Text + "<br/>" + imgHTML;
lblUploadImg.ForeColor = Color.Green;
lblUploadImg.Visible = true;
lblUploadImg.Text = "上傳文件成功!";
}
else
{
lblUploadImg.ForeColor = Color.Red;
lblUploadImg.Visible = true;
lblUploadImg.Text = "不支持格式或上傳失敗!";
}
}
catch (Exception ex)
{
CMsg.ShowException( this, ex);
}
}
{
try
{
if (!FileUploadImg.HasFile) return;
string virtualFilePath = "~//" + CAppConfiguration.Current.BbsUploadFilePath;
string savePath = this.Server.MapPath(virtualFilePath); //保存文件物理路徑
//調用CFileUpload類
CFileUpload upload = new CFileUpload(FileUploadImg, savePath, false);
//上傳圖片文件
bool ret = upload.UploadImage();
if (ret)
{
string filename = System.IO.Path.GetFileName(upload.LastUploadedFile);
string imgHTML = "<img alt=''''貼圖圖片'''' src=''''{0}'''' />";
this.hfLastUploadImage.Value = filename;
string root = CGlobals.GetHttpRoot( this);
imgHTML = string.Format(imgHTML, root + "/" + CAppConfiguration.Current.BbsUploadFilePath + filename);
FreeTextBox1.Text = FreeTextBox1.Text + "<br/>" + imgHTML;
lblUploadImg.ForeColor = Color.Green;
lblUploadImg.Visible = true;
lblUploadImg.Text = "上傳文件成功!";
}
else
{
lblUploadImg.ForeColor = Color.Red;
lblUploadImg.Visible = true;
lblUploadImg.Text = "不支持格式或上傳失敗!";
}
}
catch (Exception ex)
{
CMsg.ShowException( this, ex);
}
}