Resizing an image during upload

Thread is closed for posting
16 posts, 0 answers
  1. 63F75A2C-1F16-4AED-AFE8-B1BBD57646AD
    63F75A2C-1F16-4AED-AFE8-B1BBD57646AD avatar
    1572 posts
    Member since:
    Oct 2004

    Posted 04 Feb 2010 Link to this post

    Requirements

    RadControls version

    RadControls for ASP.NET AJAX
                      2009
    .NET version

    2.0/3./4.0
    Visual Studio version

    2005/2008/2010
    programming language C#/VB.NET
    browser support

    all browsers supported by RadControls


    PROJECT DESCRIPTION
    This code library shows how to resize the uploaded image in the RadEditor's ImageManager. The implemented FileBrowserContentProvider (ChangeImageSizeProvider) can be used with RadFileExplorer as well.
  2. 4692CD32-6D63-46B0-AA92-B22342E7F310
    4692CD32-6D63-46B0-AA92-B22342E7F310 avatar
    15 posts
    Member since:
    Jul 2007

    Posted 21 Feb 2011 Link to this post

    This code is extremely helpful and works great.

    Is there a way to pass down a size parameter, or to fetch a property of the RadEditor?

    Instead of a hardcoded size, I'd like to be able to set the reformatted size as a property of a custom radEditor.

    Thanks,

    --Tad Richard
  3. DF60784D-55A5-4263-9F10-A12FA48C9ADC
    DF60784D-55A5-4263-9F10-A12FA48C9ADC avatar
    14477 posts
    Member since:
    Apr 2022

    Posted 24 Feb 2011 Link to this post

    Hi Tad,

    You can see the following forum thread on the subject: Custom Upload File Fields, which will help you to add custom upload file fields where the user will enter the desired image dimensions and after that you will be able to obtain these values and supply them to the StoreFile / StoreBitmap functions of your file browser content provider.

    Best regards,
    Rumen
    the Telerik team
    Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
  4. 4692CD32-6D63-46B0-AA92-B22342E7F310
    4692CD32-6D63-46B0-AA92-B22342E7F310 avatar
    15 posts
    Member since:
    Jul 2007

    Posted 24 Feb 2011 Link to this post

    Rumen,

    Thanks for pointing me toward that thread, but it's not exactly what I'm trying to do.

    I have an administrative interface that uses multiple RadEditors to edit the various regions of a web page.  So for RadEditor1 (editing the main content area), I might want to reformat all the images to be no wider than 400 pixels.  And for RadEditor2 (editing the right sidebar), I might want to reformat all the images to be no wider than 200 pixels; etc.  I want this to be coded as a setting on each editor, and not set by the end user.

    What I *think* I need is a method for determining -- from within the FileBrowserContentProvider --which RadEditor control initiated the instance of the FileBrowserContentProvider.  That way, I can create a custom editor (extending RadEditor) that has a MaxImageWidth property, and get the value of that property from within the StoreFile event of the FileBrowserContentProvider.

    Not sure if it's possible, but thought I'd ask.

    Best,

    --Tad
  5. DF60784D-55A5-4263-9F10-A12FA48C9ADC
    DF60784D-55A5-4263-9F10-A12FA48C9ADC avatar
    14477 posts
    Member since:
    Apr 2022

    Posted 01 Mar 2011 Link to this post

    Hello Tad,

    The requested feature can be easily implemented on the client using as a base the solution provided in the following KB article: Resizing images proportional in Internet Explorer. You can modify the code to stop the resizing above the specified boundaries. Using editor.get_id() method you can check the id of the current editor and set the allowed width and height values for images inside this editor.

    Another approach is to use the current HttpContext object to pass parameters to the content provider. As you probably noticed, the context is part of the provider constructor. For example set the desired images paths, dimensions, editor id, etc as a value of the ViewPaths property and after that obtain this information from the constructor of the content provider, e.g.

    Set the value in the context instead of ViewPaths:
    Copy Code
    void setExplorerViewPath ()
    {
        if (!string.IsNullOrEmpty (this.XmlFilePath))
        {
            explorer.Configuration.ViewPaths = new string [] { XmlFilePath + InitialPath };
            Context.Items.Add("testItem", "testValue");
        }
    }

    Access the value inside the content provider code:
    Copy Code
    public override DirectoryItem ResolveRootDirectoryAsTree (string path)
    {
        string value = Context.Items["testItem"].ToString();
        return resolveDirectory (value, path, true, false);
    }

    If you do not want to use the context, then you can do a little hack and store the value in the ViewPath, but then change the ViewPath in the provider constructor -e.g. remove the path to the xml file and replace it with something else ("/").


    Kind regards,
    Rumen
    the Telerik team
    Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
  6. 4692CD32-6D63-46B0-AA92-B22342E7F310
    4692CD32-6D63-46B0-AA92-B22342E7F310 avatar
    15 posts
    Member since:
    Jul 2007

    Posted 02 Mar 2011 Link to this post

    Thanks for the good advice, Rumen,

    Because I wanted it all to be done server-side, I hacked the viewPath property to inject the size values when constructing the FileSystemContentProvider, and overrode the ResolveRootDirectoryAsTree method to ignore them.

    Maybe I was doing something wrong, but when I tried to modify the constructor to pull the values back out of the hacked veiwPath, it was not working.  It appeared to me that the base constructor class does something with viewPath that can't be undone by the derived class re-setting the property.

    In any case, I have it working well enough for what I need.

    Thanks, as always, for the great support.

    --Tad
  7. 1B27C03C-304E-4233-8DC3-4CCB5FA00400
    1B27C03C-304E-4233-8DC3-4CCB5FA00400 avatar
    11 posts
    Member since:
    Jun 2010

    Posted 01 Jul 2011 Link to this post

    Hi,

    I am trying to fix the widht and height of the image chosen in telerik RadEditior, i have tried with both Javascript and C# code saperately which i found in forums, but could not resolve.
    I am using V.S 2010 and telerik product version 2009.3.1103.35.

    Javascript used:

     

     

    <script type="text/javascript">  

     

    function OnClientLoad(editor, args) {  

    editor.attachEventHandler( 

    "oncontrolselect", function () {  

    //Check if image  

    window.setTimeout(

    function () {  

    var selElem = editor.getSelection().getParentElement();  

    alert(selElem.tagName); 

    if (selElem.tagName == "IMG") {  

    //Store current width and height  

    curWidth = selElem.offsetWidth;

    curHeight = selElem.offsetHeight; 

    //Possible to resize, so attach eventhandler  

    selElem.onresizeend = 

    function (e) {  

    alert("I was resized");  

    selElem.style.width = "150";  

    selElem.style.height ="150"

    selElem.onresizeend = null; //remove handler  

     

    //Make calculations about skaling, then re-size image  

    };

    }

    }, 0);

    });

    }
    Code used in C#

    The one which i have found in these attachements,
    In page_load
    { string [] paths = new string[] { "~/Images/editor" };

     

    RadEditor1.ImageManager.ViewPaths = paths;

    RadEditor1.ImageManager.UploadPaths = paths;

    RadEditor1.ImageManager.DeletePaths = paths;

    RadEditor1.ImageManager.ContentProviderTypeName =

     

    typeof(ChangeImageSizeProvider).AssemblyQualifiedName;
    }

     public class ChangeImageSizeProvider : Telerik.Web.UI.Widgets.FileSystemContentProvider 

    public ChangeImageSizeProvider(HttpContext context, string[] searchPatterns, string[] viewPaths, string[] uploadPaths, string[] deletePaths, string selectedUrl, string selectedItemTag) 

    base(context, searchPatterns, viewPaths, uploadPaths, deletePaths, selectedUrl, selectedItemTag)  

    {  

    public override string StoreFile(UploadedFile file, string path, string name, params string[] arguments)

     {
    System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream);  

    string physicalPath = Context.Server.MapPath(path); 
     int newWidth = 100;// Fixed width 
     int newHeight = 100;// Fixed height  

    System.Drawing.Image resultImage = ResizeImage(image, new Size(newWidth, newHeight));

     resultImage.Save(physicalPath + name); 

    string result = path + name; 
     return result;  

    }

     

    private System.Drawing.Image ResizeImage(System.Drawing.Image sourceImage, Size newSize)  

    Bitmap bitmap = new Bitmap(newSize.Width, newSize.Height); 
     Graphics g = Graphics.FromImage((System.Drawing.Image)bitmap);

    g.InterpolationMode = InterpolationMode.HighQualityBicubic;  

    g.DrawImage(sourceImage, 0, 0, newSize.Width, newSize.Height);

    g.Dispose();

     return (System.Drawing.Image)bitmap;  

    }

    }

     

     I have a save option with which i am saving 

     

     asdf.Content = this.RadEditor1.Content;

     asdf.save();

    Please let me know, if I need to do anything else.

    Thanks
    G Krishna

  8. DF60784D-55A5-4263-9F10-A12FA48C9ADC
    DF60784D-55A5-4263-9F10-A12FA48C9ADC avatar
    14477 posts
    Member since:
    Apr 2022

    Posted 05 Jul 2011 Link to this post

    Hi Gopi,

    You are using a very old version of RadEditor, which does not support the latest version of IE9. The oncontrolselect event is also supported only by Internet Explorer. This means that the JavaScript solution works in IE only but not in other browsers.

    As to the FileSystemContent provider it works only when uploading images via the Upload dialog of the Image manager. Note that the user will be still able to resize the images in the content area even if they are inserted with minimal size in the content area.

    You can disable the image resizing in IE by setting the unselectable="on" attribute to all IMG tags in the content area, then the browser will not display the image handlers, e.g.

    <script type="text/javascript">
    function OnClientSelectionChange(editor)
    {
    var images = editor.get_document().getElementsByTagName("IMG");
    for (var i = 0; i < images.length; i++)
    {
    var image = images[i];
    image.setAttribute("unselectable", "on");
    }
    }
    </script>

    <telerik:RadEditor ID="RadEditor1"

    OnClientSelectionChange="OnClientSelectionChange"

    runat="server" Width="100%" Height="345px">
    <Content>
    <img src="http://www.telerik.com/DEMOS/ASPNET/RadControls/Editor/Skins/Default/buttons/CustomDialog.gif"/>
    <a href="www.telerik.com">telerik</a>
    <img src="http://www.telerik.com/DEMOS/ASPNET/RadControls/Editor/Skins/Default/buttons/CustomDialog.gif"/>
    </Content>
    </telerik:RadEditor>

    The unselectable attribute is supported by IE. Opera, Chrome and Safari do not offer resize handlers for the images.

    Best regards,
    Rumen
    the Telerik team

    Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

  9. 1B27C03C-304E-4233-8DC3-4CCB5FA00400
    1B27C03C-304E-4233-8DC3-4CCB5FA00400 avatar
    11 posts
    Member since:
    Jun 2010

    Posted 05 Jul 2011 Link to this post

    Thanks Rumen, I got solution in your reply.
  10. 318E9481-64ED-4B53-B8F2-5B0B66065CB5
    318E9481-64ED-4B53-B8F2-5B0B66065CB5 avatar
    2 posts
    Member since:
    Dec 2006

    Posted 15 Mar 2012 Link to this post

    This code works great to re-size the image, but the resulting file size is way bigger than the original file size.  I am re-sizing a .jpg that is 1698x2197 at 401KB down to 800x1035 and the resulting file is 1.00 MB.  How can I keep the resulting file at the same or smaller size as the original?  I have tried all the interpolation modes, and NearestNeighbor produces the smallest output file.  I have tried setting the resolution on the output bitmap to a low value (96x96) but it seems to have no effect on the resulting file size.
  11. DF60784D-55A5-4263-9F10-A12FA48C9ADC
    DF60784D-55A5-4263-9F10-A12FA48C9ADC avatar
    14477 posts
    Member since:
    Apr 2022

    Posted 20 Mar 2012 Link to this post

    Hello,

    I think that the Save JPEG image with compression value example provided in the Image.Save Method MSDN article could be helpful for your scenario. The code available in this article is useful as well: http://msdn.microsoft.com/en-us/library/ytz20d80.aspx#Mtps_DropDownFilterText.

    Best regards,
    Rumen
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
  12. 318E9481-64ED-4B53-B8F2-5B0B66065CB5
    318E9481-64ED-4B53-B8F2-5B0B66065CB5 avatar
    2 posts
    Member since:
    Dec 2006

    Posted 21 Mar 2012 Link to this post

    Thanks, that is exactly what I needed.
  13. 02790537-9067-459B-8C5C-8C8203926291
    02790537-9067-459B-8C5C-8C8203926291 avatar
    4 posts
    Member since:
    Aug 2010

    Posted 05 Jun 2012 Link to this post

    Hello

    I create application to upload files using RadUpload control. I my case if image is too big I need to resize it automatically.
    I use this code:

    ....
    foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
    {
    System.Drawing.Image image = System.Drawing.Image.FromFile(validFile.FileName); 
    int newWidth = 100;// Fixed width
    int newHeight = 100;// Fixed height
    System.Drawing.Image resultImage = ResizeImage(image, new Size(newWidth, newHeight));

    string targetFolder = strFileLocation;
    resultImage.Save(targetFolder + validFile.GetName());
    }
    .....


    private System.Drawing.Image ResizeImage(System.Drawing.Image sourceImage, Size newSize)
            {
                Bitmap bitmap = new Bitmap(newSize.Width, newSize.Height);
                Graphics g = Graphics.FromImage((System.Drawing.Image)bitmap);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourceImage, 0, 0, newSize.Width, newSize.Height);
                g.Dispose();
                return (System.Drawing.Image)bitmap;
            }

    On Line resultImage.Save(targetFolder + validFile.GetName());
    I have this error: 
    Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

    Can you help me what I do wrong

    Thanks,
    Paul

  14. DF60784D-55A5-4263-9F10-A12FA48C9ADC
    DF60784D-55A5-4263-9F10-A12FA48C9ADC avatar
    14477 posts
    Member since:
    Apr 2022

    Posted 06 Jun 2012 Link to this post

    Hi Paul,

    This is a general .NET error, which is not directly related to RadControls. You can search in Google and find information how to fix it. For your convenience I have found the following threads which could be helpful for your scenario:
    http://stackoverflow.com/questions/1772083/when-drawing-an-image-system-runtime-interopservices-externalexception-a-gener
    http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream
    http://dotnetfish.blogspot.com/2008/04/systemruntimeinteropservicesexternalexc.html

    Regards,
    Rumen
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
  15. 6092F91C-3E5C-420D-A450-641D7662BBE2
    6092F91C-3E5C-420D-A450-641D7662BBE2 avatar
    1 posts
    Member since:
    Aug 2005

    Posted 10 Mar 2014 in reply to 63F75A2C-1F16-4AED-AFE8-B1BBD57646AD Link to this post

    Hi, is there an example of this code available that works in version 7.1.2.0?

    Thank you.
  16. DF60784D-55A5-4263-9F10-A12FA48C9ADC
    DF60784D-55A5-4263-9F10-A12FA48C9ADC avatar
    14477 posts
    Member since:
    Apr 2022

    Posted 11 Mar 2014 Link to this post

    Hi,

    You can try to use the OnFileUpload event to resize the image in the earlier version:

    Default.aspx:

    <radE:RadEditor ID="RadEditor1" Runat="server"  HasPermission="True" Width="800" Height="500"
     ToolsFile="~/RadControls/Editor/ToolsFile.xml"
    ImagesPaths="~/upload" UploadImagesPaths="~/upload"  DeleteImagesPaths="~/upload" OnFileUpload="RadEditor1_FileUpload" >
    </radE:RadEditor>


    Default.aspx.cs:
    public bool RadEditor1_FileUpload(object sender, string fileName, Telerik.WebControls.EditorFileTypes type)
            {
                string originalImageLocation = Server.MapPath(fileName);       
                this.CreateThumb(originalImageLocation, 300, 300);
                return true;
            }
     
            public void CreateThumb(string originalImageLocation, int width, int height)
            {
                System.Drawing.Image.GetThumbnailImageAbort myCallback =
                   new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
     
                //Create a copy of the image with a different size.
                Bitmap myBitmap = new Bitmap(originalImageLocation);
     
                System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
                myBitmap.Dispose();
     
                //Delete the original bitmap
                File.Delete(originalImageLocation);
     
                //Save new bitmap using the same name
                myThumbnail.Save(originalImageLocation);
                myThumbnail.Dispose();
            }
     
            public bool ThumbnailCallback()
            {
                return false;
            }



    Regards,
    Rumen
    Telerik

    DevCraft Q1'14 is here! Watch the online conference to see how this release solves your top-5 .NET challenges. Watch on demand now.

Back to Top

This Code Library is part of the product documentation and subject to the respective product license agreement.