This is a migrated thread and some comments may be shown as answers.

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

1 Answer 937 Views
AsyncUpload
This is a migrated thread and some comments may be shown as answers.
Pedro
Top achievements
Rank 1
Pedro asked on 23 Sep 2016, 02:08 PM

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

1 Answer, 1 is accepted

Sort by
0
Rumen
Telerik team
answered on 27 Sep 2016, 01:12 PM

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.
Tags
AsyncUpload
Asked by
Pedro
Top achievements
Rank 1
Answers by
Rumen
Telerik team
Share this question
or