[上传下载] C# ImageUpload图片上传类教程与源码下载 (转载)
功能如下图片
1.设置属性后上传图片,用法如下
/// <summary>
/// 图片上传类
/// </summary>
//----------------调用-------------------
//imageUpload iu = new imageUpload();
//iu.AddText = "";
//iu.CopyIamgePath = "";
//iu.DrawString_x = ;
//iu.DrawString_y = ;
//iu.DrawStyle = ;
//iu.Font = "";
//iu.FontSize = ;
//iu.FormFile = File1;
//iu.IsCreateImg =;
//iu.IsDraw = ;
//iu.OutFileName = "";
//iu.OutThumbFileName = "";
//iu.SavePath = @"~/image/";
//iu.SaveType = ;
//iu.sHeight = ;
//iu.sWidth = ;
//iu.Upload();
//--------------------------------------
代码如下
/// <summary>
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:[url=http://www.sufeinet.com/thread-655-1-1.html]http://www.sufeinet.com/thread-655-1-1.html[/url]
/// </summary>
using System;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Drawing; namespace DotNet.Utilities
{
/// <summary>
/// 文件类型
/// </summary>
public enum FileExtension
{
JPG = ,
GIF = ,
BMP = ,
PNG = ,
RAR = ,
jpg = ,
exe = ,
xml = ,
html = ,
aspx = ,
cs = ,
js = ,
txt = ,
sql =
} /// <summary>
/// 图片检测类
/// </summary>
public static class FileValidation
{
#region 上传图片检测类
/// <summary>
/// 是否允许
/// </summary>
public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx)
{
int fileLen = oFile.ContentLength;
byte[] imgArray = new byte[fileLen];
oFile.InputStream.Read(imgArray, , fileLen);
MemoryStream ms = new MemoryStream(imgArray);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
string fileclass = "";
byte buffer;
try
{
buffer = br.ReadByte();
fileclass = buffer.ToString();
buffer = br.ReadByte();
fileclass += buffer.ToString();
}
catch { }
br.Close();
ms.Close();
foreach (FileExtension fe in fileEx)
{
if (Int32.Parse(fileclass) == (int)fe) return true;
}
return false;
} /// <summary>
/// 上传前的图片是否可靠
/// </summary>
public static bool IsSecureUploadPhoto(HttpPostedFile oFile)
{
bool isPhoto = false;
string fileExtension = System.IO.Path.GetExtension(oFile.FileName).ToLower();
string[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = ; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions)
{
isPhoto = true;
break;
}
}
if (!isPhoto)
{
return true;
}
FileExtension[] fe = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG }; if (IsAllowedExtension(oFile, fe))
return true;
else
return false;
} /// <summary>
/// 上传后的图片是否安全
/// </summary>
/// <param name="photoFile">物理地址</param>
public static bool IsSecureUpfilePhoto(string photoFile)
{
bool isPhoto = false;
string Img = "Yes";
string fileExtension = System.IO.Path.GetExtension(photoFile).ToLower();
string[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = ; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions)
{
isPhoto = true;
break;
}
} if (!isPhoto)
{
return true;
}
StreamReader sr = new StreamReader(photoFile, System.Text.Encoding.Default);
string strContent = sr.ReadToEnd();
sr.Close();
string str = "request|<script|.getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language=";
foreach (string s in str.Split('|'))
{
if (strContent.ToLower().IndexOf(s) != -)
{
File.Delete(photoFile);
Img = "No";
break;
}
}
return (Img == "Yes");
}
#endregion
} /// <summary>
/// 图片上传类
/// </summary>
//----------------调用-------------------
//imageUpload iu = new imageUpload();
//iu.AddText = "";
//iu.CopyIamgePath = "";
//iu.DrawString_x = ;
//iu.DrawString_y = ;
//iu.DrawStyle = ;
//iu.Font = "";
//iu.FontSize = ;
//iu.FormFile = File1;
//iu.IsCreateImg =;
//iu.IsDraw = ;
//iu.OutFileName = "";
//iu.OutThumbFileName = "";
//iu.SavePath = @"~/image/";
//iu.SaveType = ;
//iu.sHeight = ;
//iu.sWidth = ;
//iu.Upload();
//--------------------------------------
public class ImageUpload
{
#region 私有成员
private int _Error = ;//返回上传状态。
private int _MaxSize = * ;//最大单个上传文件 (默认)
private string _FileType = "jpg;gif;bmp;png";//所支持的上传类型用"/"隔开
private string _SavePath = System.Web.HttpContext.Current.Server.MapPath(".") + "\\";//保存文件的实际路径
private int _SaveType = ;//上传文件的类型,0代表自动生成文件名
private HtmlInputFile _FormFile;//上传控件。
private string _InFileName = "";//非自动生成文件名设置。
private string _OutFileName = "";//输出文件名。
private bool _IsCreateImg = true;//是否生成缩略图。
private bool _Iss = false;//是否有缩略图生成.
private int _Height = ;//获取上传图片的高度
private int _Width = ;//获取上传图片的宽度
private int _sHeight = ;//设置生成缩略图的高度
private int _sWidth = ;//设置生成缩略图的宽度
private bool _IsDraw = false;//设置是否加水印
private int _DrawStyle = ;//设置加水印的方式0:文字水印模式,1:图片水印模式,2:不加
private int _DrawString_x = ;//绘制文本的X坐标(左上角)
private int _DrawString_y = ;//绘制文本的Y坐标(左上角)
private string _AddText = "GlobalNatureCrafts";//设置水印内容
private string _Font = "宋体";//设置水印字体
private int _FontSize = ;//设置水印字大小
private int _FileSize = ;//获取已经上传文件的大小
private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//图片水印模式下的覆盖图片的实际地址
#endregion #region 公有属性
/// <summary>
/// Error返回值
/// 1、没有上传的文件
/// 2、类型不允许
/// 3、大小超限
/// 4、未知错误
/// 0、上传成功。
/// </summary>
public int Error
{
get { return _Error; }
} /// <summary>
/// 最大单个上传文件
/// </summary>
public int MaxSize
{
set { _MaxSize = value; }
} /// <summary>
/// 所支持的上传类型用";"隔开
/// </summary>
public string FileType
{
set { _FileType = value; }
} /// <summary>
/// 保存文件的实际路径
/// </summary>
public string SavePath
{
set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
get { return _SavePath; }
} /// <summary>
/// 上传文件的类型,0代表自动生成文件名
/// </summary>
public int SaveType
{
set { _SaveType = value; }
} /// <summary>
/// 上传控件
/// </summary>
public HtmlInputFile FormFile
{
set { _FormFile = value; }
} /// <summary>
/// 非自动生成文件名设置。
/// </summary>
public string InFileName
{
set { _InFileName = value; }
} /// <summary>
/// 输出文件名
/// </summary>
public string OutFileName
{
get { return _OutFileName; }
set { _OutFileName = value; }
} /// <summary>
/// 输出的缩略图文件名
/// </summary>
public string OutThumbFileName
{
get;
set;
} /// <summary>
/// 是否有缩略图生成.
/// </summary>
public bool Iss
{
get { return _Iss; }
} /// <summary>
/// 获取上传图片的宽度
/// </summary>
public int Width
{
get { return _Width; }
} /// <summary>
/// 获取上传图片的高度
/// </summary>
public int Height
{
get { return _Height; }
} /// <summary>
/// 设置缩略图的宽度
/// </summary>
public int sWidth
{
get { return _sWidth; }
set { _sWidth = value; }
} /// <summary>
/// 设置缩略图的高度
/// </summary>
public int sHeight
{
get { return _sHeight; }
set { _sHeight = value; }
} /// <summary>
/// 是否生成缩略图
/// </summary>
public bool IsCreateImg
{
get { return _IsCreateImg; }
set { _IsCreateImg = value; }
} /// <summary>
/// 是否加水印
/// </summary>
public bool IsDraw
{
get { return _IsDraw; }
set { _IsDraw = value; }
} /// <summary>
/// 设置加水印的方式
/// 0:文字水印模式
/// 1:图片水印模式
/// 2:不加
/// </summary>
public int DrawStyle
{
get { return _DrawStyle; }
set { _DrawStyle = value; }
} /// <summary>
/// 绘制文本的X坐标(左上角)
/// </summary>
public int DrawString_x
{
get { return _DrawString_x; }
set { _DrawString_x = value; }
} /// <summary>
/// 绘制文本的Y坐标(左上角)
/// </summary>
public int DrawString_y
{
get { return _DrawString_y; }
set { _DrawString_y = value; }
} /// <summary>
/// 设置文字水印内容
/// </summary>
public string AddText
{
get { return _AddText; }
set { _AddText = value; }
} /// <summary>
/// 设置文字水印字体
/// </summary>
public string Font
{
get { return _Font; }
set { _Font = value; }
} /// <summary>
/// 设置文字水印字的大小
/// </summary>
public int FontSize
{
get { return _FontSize; }
set { _FontSize = value; }
} /// <summary>
/// 文件大小
/// </summary>
public int FileSize
{
get { return _FileSize; }
set { _FileSize = value; }
} /// <summary>
/// 图片水印模式下的覆盖图片的实际地址
/// </summary>
public string CopyIamgePath
{
set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
} #endregion #region 私有方法
/// <summary>
/// 获取文件的后缀名
/// </summary>
private string GetExt(string path)
{
return Path.GetExtension(path);
} /// <summary>
/// 获取输出文件的文件名
/// </summary>
private string FileName(string Ext)
{
if (_SaveType == || _InFileName.Trim() == "")
return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
else
return _InFileName;
} /// <summary>
/// 检查上传的文件的类型,是否允许上传。
/// </summary>
private bool IsUpload(string Ext)
{
Ext = Ext.Replace(".", "");
bool b = false;
string[] arrFileType = _FileType.Split(';');
foreach (string str in arrFileType)
{
if (str.ToLower() == Ext.ToLower())
{
b = true;
break;
}
}
return b;
}
#endregion #region 上传图片
public void Upload()
{
HttpPostedFile hpFile = _FormFile.PostedFile;
if (hpFile == null || hpFile.FileName.Trim() == "")
{
_Error = ;
return;
}
string Ext = GetExt(hpFile.FileName);
if (!IsUpload(Ext))
{
_Error = ;
return;
}
int iLen = hpFile.ContentLength;
if (iLen > _MaxSize)
{
_Error = ;
return;
}
try
{
if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
byte[] bData = new byte[iLen];
hpFile.InputStream.Read(bData, , iLen);
string FName;
FName = FileName(Ext);
string TempFile = "";
if (_IsDraw)
{
TempFile = FName.Split('.').GetValue().ToString() + "_temp." + FName.Split('.').GetValue().ToString();
}
else
{
TempFile = FName;
}
FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
newFile.Write(bData, , bData.Length);
newFile.Flush();
int _FileSizeTemp = hpFile.ContentLength; string ImageFilePath = _SavePath + FName;
if (_IsDraw)
{
if (_DrawStyle == )
{
System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
Graphics g = Graphics.FromImage(Img1);
g.DrawImage(Img1, , , Img1.Width, Img1.Height);
Font f = new Font(_Font, _FontSize);
Brush b = new SolidBrush(Color.Red);
string addtext = _AddText;
g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
g.Dispose();
Img1.Save(ImageFilePath);
Img1.Dispose();
}
else
{
System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
Graphics g = Graphics.FromImage(image);
g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - , image.Height - copyImage.Height - , copyImage.Width, copyImage.Height), , , copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
g.Dispose();
image.Save(ImageFilePath);
image.Dispose();
}
} //获取图片的高度和宽度
System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
_Width = Img.Width;
_Height = Img.Height; //生成缩略图部分
if (_IsCreateImg)
{
#region 缩略图大小只设置了最大范围,并不是实际大小
float realbili = (float)_Width / (float)_Height;
float wishbili = (float)_sWidth / (float)_sHeight; //实际图比缩略图最大尺寸更宽矮,以宽为准
if (realbili > wishbili)
{
_sHeight = (int)((float)_sWidth / realbili);
}
//实际图比缩略图最大尺寸更高长,以高为准
else
{
_sWidth = (int)((float)_sHeight * realbili);
}
#endregion this.OutThumbFileName = FName.Split('.').GetValue().ToString() + "_s." + FName.Split('.').GetValue().ToString();
string ImgFilePath = _SavePath + this.OutThumbFileName; System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
newImg.Save(ImgFilePath);
newImg.Dispose();
_Iss = true;
} if (_IsDraw)
{
if (File.Exists(_SavePath + FName.Split('.').GetValue().ToString() + "_temp." + FName.Split('.').GetValue().ToString()))
{
newFile.Dispose();
File.Delete(_SavePath + FName.Split('.').GetValue().ToString() + "_temp." + FName.Split('.').GetValue().ToString());
}
}
newFile.Close();
newFile.Dispose();
_OutFileName = FName;
_FileSize = _FileSizeTemp;
_Error = ;
return;
}
catch (Exception ex)
{
_Error = ;
return;
}
}
#endregion
}
}
[上传下载] C# ImageUpload图片上传类教程与源码下载 (转载)的更多相关文章
- [GDI+] C# ImageDown帮助类教程与源码下载 (转载)
点击下载 ImageDown.zip 1.下载图片到本地代码如下 /// <summary> /// 编 码 人:苏飞 /// 联系方式:361983679 /// 更新网站:[url=h ...
- [IO] C# DirFileHelper文件与文件夹操作类教程与源码下载 (转载)
点击下载 DirFileHelper.zip 主要功能如下所示 // 摘要: // 向文本文件的尾部追加内容 // // 参数: // filePath: // 文件的绝对路径 // // conte ...
- [GDI+] C# ImageClass帮助类教程与源码下载 (转载)
点击下载 ImageClass.rar 功能如下图片 主要功能有:缩略图片,图片水印,文字水印,调整光暗,反色处理,浮雕处理,拉伸处理,左右翻转,上下翻转,压缩图片,图片灰度化,转换为黑白图片,获取图 ...
- [网络] C# NetHelper网络通信编程类教程与源码下载
点击下载 NetHelper.zip 主要功能如下所示 检查设置的IP地址是否正确,返回正确的IP地址 检查设置的端口号是否正确,返回正确的端口号 将字符串形式的IP地址转换成IPAddress对象 ...
- ExcelReport.cs Excel操作类、实例源码下载
标题一.告别ASP.NET操作EXCEL的烦恼标题二.ASP.NET操作EXCEL 合并单元格 大全... cnblogs/hanzhaoxin/韩兆新的博客园ExcelReport第一篇:使用Exc ...
- 50余本中外Python电子教程及源码下载地址
链接:http://pan.baidu.com/s/1c0VTwsC 密码:hapu
- 高仿精仿微信应用ios源码下载
微信,超过3亿人使用,能够通过手机网络给好友发送语音.文字消息.表情.图片和视频,还可以分享照片到朋友圈.通过摇一摇.查看附近的人,你可以认识新的朋友.使用扫一扫,你可以扫描二维码.条码.图书和街景. ...
- 【Android 系统开发】CyanogenMod 13.0 源码下载 编译 ROM 制作 ( 手机平台 : 小米4 | 编译平台 : Ubuntu 14.04 LTS 虚拟机)
分类: Android 系统开发(5) 作者同类文章X 版权声明:本文为博主原创文章 ...
- asp.net+swfupload 多图片批量上传(附源码下载)
asp.net的文件上传都是单个文件上传方式,无法执行一次性多张图片批量上传操作,要实现多图片批量上传需要借助于flash,通过flash选取多个图片(文件),然后再通过后端服务进行上传操作. 本次教 ...
随机推荐
- VirtualBox设置共享文件夹和镜像访问的方法
VirtualBox设置共享文件夹和镜像访问的方法 virtualBox是一款虚拟机软件,可以在该软件上安装各类的操作系统,至于如何安装请参见另外一篇经验<如何使用VirtualBox安装win ...
- 转自 x_x_的百度空间 搞ACM的你伤不起
来源:http://roba.rushcj.com/?p=548 劳资六年前开始搞ACM啊!!!!!!!!!! 从此踏上了尼玛不归路啊!!!!!!!!!!!! 谁特么跟劳资讲算法是程序设计的核心啊!! ...
- sql server 2005+ 行转列
)) , 'aa') , 'bb') , 'aaa') , 'bbb') , 'ccc') go , , '') from tb group by id
- NET Framework GAC目录构造
转:http://www.yl1001.com/userzone.htm?doaction=article&art_id=5851381388387201 我们一般都知道,.NET Frame ...
- [原]RobotFrameWork(十一)AutoItLibrary测试库在win7(64bit)下安装及简单使用
最近安装AutoItLibrary,发现在win7 x64下无法安装成功,后来经过定位,发现是3rdPartyTools\AutoIt目录下面AutoItX3.dll的问题.因为AutoItX3.dl ...
- linux时间设置相关
1.查询时间命令:date 2.设置日期:date -s mm/dd/yyyy 3.设置时间:date -s HH:MM:SS 4.将当前时间及日期写入BIOS,避免重启失效:hwclock -w 5 ...
- 路径和 二叉树 leecode
题目不难,很快ac,纯粹靠手感.https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ /** * Definition for bina ...
- action使用大全
1.Intent的用法: (1)Action跳转 1. 使用Action跳转,当程序AndroidManifest.xml中某一个 Activity的IntentFilter定义了包含Action, ...
- Genymotion常见问题汇总(转)
为什么说是常见问题整合呢,因为我就是Genymotion最悲剧的使用者,该见过的问题,我基本都见过了,在此总结出这血的教训,望大家不要重蹈覆辙. 常见问题1:Genymotion在开启模拟器时 ...
- NIO组件Selector调用实例
*对于nio的非阻塞I/O操作,使用Selector获取哪些I/O准备就绪,注册的SelectionKey集合记录关联的Channel这些信息.SelectionKey记录Channel对buffer ...