C#上传图片和生成缩略图以及图片预览

时间:2023-03-09 01:53:14
C#上传图片和生成缩略图以及图片预览

因工作需要,上传图片要增加MIME类型验证和生成较小尺寸的图片用于浏览。根据网上代码加以修改做出如下效果图:

C#上传图片和生成缩略图以及图片预览

前台代码如下:

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>上传图片和生成缩略图以及图片预览</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>图片上传:
</td>
<td>
<input type="text" id="txtImgPath" class="easyui-textbox" runat="server" style="width: 235px;" />
<input type="button" id="btnPCImg" value="浏览..." onclick="showFileUp('FileUpload1')"
class="easyui-linkbutton btn" style="width: 106px;" />
<asp:FileUpload class="easyui-linkbutton btn" Style="display: none" ID="FileUpload1"
runat="server" onchange="apendtoText('txtImgPath',this)" />
<asp:Button class="easyui-linkbutton btn" ID="btnUpFile" runat="server" Text="上传图片"
OnClick="btnUpFile_OnClick" Width="106px" />
</td>
</tr>
<tr>
<td>图片预览:
</td>
<td>
<asp:Image ID="Image1" runat="server" />
<asp:TextBox ID="txtimg" Style="display: none;" runat="server" Height="20px"></asp:TextBox>
<asp:TextBox ID="oldimgpath" Style="display: none;" runat="server" Height="20px"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
<script type="text/javascript">
/*
* 显示文件选择框
* id {String} 要显示的FileUp
*/
function showFileUp(id) {
$('#' + id).click();
}
/*
* FileUp控件值改变后将该控件的值赋给其他控件
* id {String} 接收值的控件ID
* obj {Object} FileUp控件
*/
function apendtoText(id, obj) {
$('#' + id).textbox('setText', $(obj).val());
}
</script>
</html>

后台代码如下:

         /// <summary>
/// 上传图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpFile_OnClick(object sender, EventArgs e)
{
if (FileUpload1.PostedFile.FileName != "")
{
if (FileUpload1.PostedFile.ContentLength <= )//只能上传小于或等于2MB的图片
{
FileExtension[] fe = { FileExtension.Gif, FileExtension.Jpg, FileExtension.Png };//允许的图片格式
if (FileValidation.IsAllowedExtension(FileUpload1, fe))
{
//}
//if (newFileExtensions == ".jpg" || newFileExtensions == ".gif" || newFileExtensions == ".bmp" || newFileExtensions == ".png")//直接使用文件后缀检查是否为允许类型
//{
string sfilename = FileUpload1.PostedFile.FileName;
int sfilenamehz = sfilename.LastIndexOf(".", StringComparison.Ordinal);
string newFileExtensions = sfilename.Substring(sfilenamehz).ToLower();
string pa = "uploadfiles/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "/";//获取当前年份和月份作为文件夹名
if (!Directory.Exists("~/" + pa))//如不存在则创建文件夹
{
Directory.CreateDirectory(Server.MapPath("~/" + pa));
}
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
string uppath = "~/" + pa + newFileName + newFileExtensions; Stream oStream = FileUpload1.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream); int oWidth = oImage.Width; //原图宽度
int oHeight = oImage.Height; //原图高度
int tWidth = ; //设置缩略图初始宽度
int tHeight = ; //设置缩略图初始高度 //按比例计算出缩略图的宽度和高度
if (oWidth >= oHeight)
{
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
}
else
{
tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
} //生成缩略原图
Bitmap tImage = new Bitmap(tWidth, tHeight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
g.Clear(Color.Transparent); //清空画布并以透明背景色填充
g.DrawImage(oImage, new Rectangle(, , tWidth, tHeight), new Rectangle(, , oWidth, oHeight), GraphicsUnit.Pixel); string upfilepath2 = "~/" + pa + newFileName + "_m" + newFileExtensions; //缩略图为原图后缀增加_m用于区分
string oFullName = Server.MapPath(uppath);
string tFullName = Server.MapPath(upfilepath2); try
{
//保存图片
oImage.Save(oFullName);
tImage.Save(tFullName);
Image1.ImageUrl = upfilepath2;//将缩略图显示到前台Img控件
txtimg.Text = pa + newFileName + "_m" + newFileExtensions;//将文件地址赋予控件用于保存
}
catch (Exception ex)
{
throw new Exception("发生错误,保存失败!", ex);
}
finally
{
//释放资源
oImage.Dispose();
g.Dispose();
tImage.Dispose();
}
}
else
{
string fileType = string.Empty;
foreach (var fileExtension in fe)
{
if (!string.IsNullOrEmpty(fileType))
{
fileType += ",";
}
fileType += fileExtension;
}
Response.Write("<script>alert('文件格式被禁止,只支持" + fileType + "格式的图片')</script>");
}
}
else
{
Response.Write("<script>alert('文件大了,请修改大小,勿超过2MB')</script>");
}
}
}
enum FileExtension
{
Jpg = ,
Gif = ,
Png =
}
/// <summary>
/// 判断上传的文件的真实格式
/// </summary>
private class FileValidation
{
/// <summary>
/// 检查是否为允许的图片格式
/// </summary>
/// <param name="fu">上传控件</param>
/// <param name="fileEx">文件扩展名</param>
/// <returns></returns>
public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
{
int fileLen = fu.PostedFile.ContentLength;
byte[] imgArray = new byte[fileLen];
fu.PostedFile.InputStream.Read(imgArray, , fileLen);
MemoryStream ms = new MemoryStream(imgArray);
BinaryReader br = new BinaryReader(ms);
string fileclass = string.Empty;
try
{
byte buffer = br.ReadByte();
fileclass = buffer.ToString();
buffer = br.ReadByte();
fileclass += buffer.ToString();
}
catch //(Exception ex)
{
// ignored
}
br.Close();
ms.Close();
int num = ;
int.TryParse(fileclass, out num);
foreach (FileExtension fe in fileEx)
{
if (num == (int)fe)
return true;
}
return false;
}
}