How can I check and validate dimensions of a picture before upload?

2 posts, 0 answers
  1. Pedro
    Pedro avatar
    2 posts
    Member since:
    Jul 2016

    Posted 23 Sep Link to this post

    In my web application I use a AsyncUpload to load the picture of each user to their personal page.
    I need to limit the dimensions (height and width) of uploaded images.

    How can I validate the height and width of the images before they are loaded? Or convert them to the dimensions I want?
    I need images have the dimensions 150x100
    I have the following code to validate file type and file size of uploaded images.

    foreach (UploadedFile file in LogoUpload.UploadedFiles)
        {
            //string filetype = LogoUpload.PostedFile.ContentType;
            string filetype = file.ContentType;
            long filesize = file.ContentLength;
            byte [] input = new byte[filesize - 1];
     
            long maxFileSize = 1024;
     
            if (filesize > maxFileSize)
            {
                base.OnUIValidation("The file is too big.");
                return;
            }
     
            string[] acceptedFileTypes = new string[3];
            acceptedFileTypes[0] = "image/jpg";
            acceptedFileTypes[1] = "image/jpeg";
            acceptedFileTypes[2] = "image/jpeg";
     
            bool acceptFile = false;
     
     
            //should we accept the file?
            for (int i = 0; i <= 2; i++)
            {
                if (filetype == acceptedFileTypes[i])
                {
                    //accept the file, yay!
                    acceptFile = true;
                }
                 }

    I have aI have a RadUpload
  2. Rumen
    Admin
    Rumen avatar
    12846 posts

    Posted 27 Sep Link to this post

    Hi Pedro,

    You can validate the image dimensions by converting the InputStream of the uploaded file into a Bitmap and check its Height and Width properties in the FileUploaded event handler. Here is a sample implementation of the described approach:

    <telerik:RadAsyncUpload RenderMode="Lightweight" ID="RadAsyncUpload1"
        OnFileUploaded="RadAsyncUpload1_FileUploaded" PostbackTriggers="Button1"
        runat="server">
    </telerik:RadAsyncUpload>
    <asp:Button Text="Upload Images" ID="Button1" runat="server" />

    Copy Code
    protected void RadAsyncUpload1_FileUploaded(object sender, Telerik.Web.UI.FileUploadedEventArgs e)
    {
        using (Bitmap originalImage = new Bitmap(e.File.InputStream))
        {
            var width = originalImage.Width;
            var height = originalImage.Height;
        }
    }


    Here are some resources you might also find useful:



    Best regards,

    Rumen
    Telerik by Progress
    Do you need help with upgrading your ASP.NET AJAX, WPF or WinForms projects? Check the Telerik API Analyzer and share your thoughts.
  3. UI for ASP.NET Ajax is Ready for VS 2017
Back to Top