-1

我的网页有文件上传选项..它必须检查两个条件。1)所选项目是否为图像..如果图像表示则仅允许用户执行,否则不会。2)检查选定的图像尺寸(它只允许有限的尺寸)

4

2 回答 2

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;
}
于 2012-06-25T05:17:05.733 回答
0
  1. 您可以使用 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>
    
  2. 在 web.config 中设置图像最大尺寸

    <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="524288"/>
      </requestFiltering>
    </security>
    </system.webServer>
    
于 2012-06-25T05:40:22.157 回答