我的网页有文件上传选项..必须检查两个条件。 1)所选项目是否是图像..如果图像意味着它只允许用户以其他方式执行。 2)检查所选的图像尺寸(仅允许有限的尺寸)
答案 0 :(得分:0)
要判断文件是否为图像,只需查看扩展名(System.File.Path.GetExtension)。您可以轻松调整图像大小,并确保它不超过一定的大小:
public static Bitmap CreateThumbnail(Bitmap loBMP, int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;
try
{
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int)lnTemp;
}
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
}
catch
{
return null;
}
return bmpOut;
}
答案 1 :(得分:0)
您可以使用RegularExpressionValidator
来简化 <asp:FileUpload ID="UploadFile" runat="server" />
<asp:RegularExpressionValidator id="UpLoadValidator" runat="server" ErrorMessage="Upload Images only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.png|.bmp|.jpeg|.gif)$" ControlToValidate="FileUpload1"> </asp:RegularExpressionValidator>
在web.config中设置图像最大大小
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="524288"/>
</requestFiltering>
</security>
</system.webServer>