RadEditor restricting image width and height

9 posts, 1 answers
  1. MPatt
    MPatt avatar
    8 posts
    Member since:
    Dec 2007

    Posted 13 Jul 2009 Link to this post

    Is there any way of restricting the maximum width and height of images that people can use within the RadEditor?  Both at the point of upload and within the designer would be useful.

    Users can upload images but some are uploading images that are far too large (dimensions) and they are breaking the layout of the page.

    I think that one partial solution would be to override the save function in the image manager to resize the graphic but the user could still use the design view of the editor to drag the image to a size that is too large.

    Thanks

  2. Rumen
    Admin
    Rumen avatar
    14351 posts

    Posted 15 Jul 2009 Link to this post

    Hi MPatt,

    The following code will get you started:

    <script type="text/javascript">   
    function OnClientLoad(editor, args)        
    {        
        editor.attachEventHandler("oncontrolselect"function()        
        {        
            //Check if image        
            window.setTimeout(function()        
            {        
                var selElem = editor.getSelection().getParentElement();         
                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 = "300";    
                        selElem.style.height = "300";    
                            
                        selElem.onresizeend = null;//remove handler       
                               
                        //Make calculations about skaling, then re-size image       
                    };   
                }     
            }, 0);        
        });    
    }        
    </script>     
    <br /><br /><br />   
    <telerik:RadEditor ID="RadEditor1"    
        OnClientLoad="OnClientLoad" ToolbarMode="showOnFocus"   
        runat="server"  Width="400" Height="400">   
        <Content>test   
          <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>   

    You will notice that when you select an image and resize it an event will fire.
    There is also most of the logic you need to get the job finished.

    Due to the lack of onresizeend event in FireFox, there does not seem to be an approach that can make things work as needed there. Hopefully, the FireFox team will eventually add this useful event to the browser's implementation (similar to the lack of onpaste event which was eventually introduced in FF3).

    You can also implement you own file system content provider on the server which will allow you to resize the images when they are uploaded to the server:

        protected void Page_Load(object sender, EventArgs e) 
        { 
            RadEditor1.ImageManager.ViewPaths = new string[]{"~/"}; 
            RadEditor1.ImageManager.UploadPaths = new string[] { "~/" }; 
            RadEditor1.ImageManager.ContentProviderTypeName = typeof(myprovider).AssemblyQualifiedName; 
        } 
     
        public class myprovider : Telerik.Web.UI.Widgets.FileSystemContentProvider 
        { 
     
            public myprovider(HttpContext context, string[] searchPatterns, string[] viewPaths, string[] uploadPaths, string[] deletePaths, string selectedUrl, string selectedItemTag) 
                : base(context, searchPatterns, viewPaths, uploadPaths, deletePaths, selectedUrl, selectedItemTag) 
            { 
            } 
     
            public bool ThumbnailCallback() 
            { 
                return false
            } 
     
            public override string StoreFile(UploadedFile file, string path, string name, params string[] arguments) 
            { 
     
                string result = base.StoreFile(file, path, name, arguments); 
     
                System.Drawing.Image.GetThumbnailImageAbort myCallback = 
                    new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 
     
                string fileName = Path.Combine(path, name); 
                //Create a copy of the image with a different size 
                using (System.Drawing.Image originalImage = Bitmap.FromStream(file.InputStream)) 
                { 
                    using (System.Drawing.Image thumbnail = originalImage.GetThumbnailImage(300, 300, myCallback, IntPtr.Zero)) 
                    { 
                        thumbnail.Save(Context.Server.MapPath(fileName)); 
                    } 
                } 
     
                return result; 
            } 
        } 



    Sincerely yours,
    Rumen
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  3. MPatt
    MPatt avatar
    8 posts
    Member since:
    Dec 2007

    Posted 16 Jul 2009 Link to this post

    Many thanks for the very helpful response.  I'll have a look into it.
    Regards,
    Matt
  4. Dimo
    Dimo avatar
    24 posts
    Member since:
    Nov 2008

    Posted 22 Apr 2010 Link to this post

    Hi!
    How can I set explicitely size to all pictures to be not more than 150px for example. Serverside prefered, but clientside also can be interesting.
  5. Rumen Jekov
    Rumen Jekov avatar
    70 posts
    Member since:
    Apr 2004

    Posted 22 Apr 2010 Link to this post

    Hi,

    This could be helpful:

    http://www.telerik.com/community/code-library/aspnet-ajax/editor/resizing-an-image-during-upload.aspx

    Of course you can also try to enhance the provided client side code posted on Jul 15, 2009 (the first snippet).

    Best regards,
    Rumen



  6. Grey
    Grey avatar
    6 posts
    Member since:
    Nov 2009

    Posted 24 Nov 2010 Link to this post

    Hi

    I wanted to resize images to a maximum width (In my case 600px) and retain the aspect ratio.

    So I modified the VB script in the code example at
    http://www.telerik.com/community/code-library/aspnet-ajax/editor/resizing-an-image-during-upload.aspx

    As Follows
    Imports System.Drawing
    Imports System.Drawing.Drawing2D
    Imports Telerik.Web.UI
     
    Partial Class Default_Vb
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            Dim paths As String() = New String() {"~/Images"}
            RadEditor1.ImageManager.ViewPaths = paths
            RadEditor1.ImageManager.UploadPaths = paths
            RadEditor1.ImageManager.DeletePaths = paths
            RadEditor1.ImageManager.ContentProviderTypeName = GetType(ChangeImageSizeProvider).AssemblyQualifiedName
        End Sub
     
     
        Public Class ChangeImageSizeProvider
            Inherits Telerik.Web.UI.Widgets.FileSystemContentProvider
     
            Public Sub New(ByVal context As HttpContext, ByVal searchPatterns As String(), ByVal viewPaths As String(), ByVal uploadPaths As String(), ByVal deletePaths As String(), ByVal selectedUrl As String, _
             ByVal selectedItemTag As String)
                MyBase.New(context, searchPatterns, viewPaths, uploadPaths, deletePaths, selectedUrl, _
                 selectedItemTag)
            End Sub
     
    Public Overloads Overrides Function StoreFile(ByVal file As UploadedFile, ByVal path As String, ByVal name As String, ByVal ParamArray arguments As String()) As String
                Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(file.InputStream)
                Dim physicalPath As String = Context.Server.MapPath(path)
                'Set Maximum Width of Image
                Dim ImageMaxwidth As Integer = 600
     
                ' Finds height and width of original image
                Dim OriginalHeight As Single = Image.Height
                Dim OriginalWidth As Single = Image.Width
                ' Finds height and width of resized image
                Dim NewWidth As Integer
                Dim NewHeight As Integer
     
                If OriginalWidth >= ImageMaxwidth Then
     
                    If OriginalHeight > OriginalWidth Then
                        NewHeight = ImageMaxwidth
                        NewWidth = (OriginalWidth / OriginalHeight) * ImageMaxwidth
                    Else
                        NewWidth = ImageMaxwidth
                        NewHeight = (OriginalHeight / OriginalWidth) * ImageMaxwidth
                    End If
     
                    'Mycode
                Else
                    NewHeight = OriginalHeight
                    NewWidth = OriginalWidth
     
     
                    'My Code
                End If
     
     
                Dim resultImage As System.Drawing.Image = ResizeImage(image, New Size(newWidth, newHeight))
                resultImage.Save(physicalPath + name)
     
                Dim result As String = path + name
                Return result
            End Function
     
            Private Function ResizeImage(ByVal sourceImage As System.Drawing.Image, ByVal newSize As Size) As System.Drawing.Image
                Dim bitmap As New Bitmap(newSize.Width, newSize.Height)
                Dim g As Graphics = Graphics.FromImage(DirectCast(bitmap, System.Drawing.Image))
                g.InterpolationMode = InterpolationMode.HighQualityBicubic
                g.CompositingQuality = CompositingQuality.HighQuality
                g.SmoothingMode = SmoothingMode.HighQuality
                g.DrawImage(sourceImage, 0, 0, newSize.Width, newSize.Height)
                g.Dispose()
     
                Return DirectCast(bitmap, System.Drawing.Image)
            End Function
        End Class
     
    End Class


    You can just set the ImageMaxWidth variable to whatever you'd like

    Oh, and I just tweaked the resize quality a bit by adding the following

    g.CompositingQuality = CompositingQuality.HighQuality
    g.SmoothingMode = SmoothingMode.HighQuality

    Works like a charm.

    Thanks for the original code, really savied me a lot of time and effort.
  7. Dobromir
    Admin
    Dobromir avatar
    1633 posts

    Posted 29 Nov 2010 Link to this post

    Hi Grey,

    Thank you for sharing your solution with the community. As a small token of gratitude I have updated your Telerik points.

    All the best,
    Dobromir
    the Telerik team
    Browse the vast support resources we have to jumpstart 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.
  8. Mattias Moberg
    Mattias Moberg avatar
    18 posts
    Member since:
    Aug 2009

    Posted 14 Jan 2011 Link to this post

    Thanks for handle nice example.
    Is there anyone that can convert Grey´s code to C# ?

    Thanks,


    Edit: Did convert it myslef.

    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);
            //Set Maximum Width of Image
            int ImageMaxwidth = 600;
     
            // Finds height and width of original image
            float OriginalHeight = image.Height;
            float OriginalWidth = image.Width;
            // Finds height and width of resized image
            int NewWidth = 0;
            int NewHeight = 0;
     
            if (OriginalWidth >= ImageMaxwidth)
            {
     
                if (OriginalHeight > OriginalWidth)
                {
                    NewHeight = ImageMaxwidth;
                    NewWidth = (int)(OriginalWidth / OriginalHeight * ImageMaxwidth);
                }
                else
                {
                    NewWidth = ImageMaxwidth;
                    NewHeight = (int)(OriginalHeight / OriginalWidth * ImageMaxwidth);
                }
     
            }
            else
            {
                NewHeight = (int)OriginalHeight;
                NewWidth = (int)OriginalWidth;
            }
     
     
            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.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(sourceImage, 0, 0, newSize.Width, newSize.Height);
            g.Dispose();
     
            return (System.Drawing.Image)bitmap;
        }
    }
  9. Answer
    Marco Antonio
    Marco Antonio avatar
    4 posts
    Member since:
    Jun 2013

    Posted 26 Sep 2013 Link to this post

    Código adaptado para limitar largura e a altura de forma proporcional!



    /******************************************************************************************************************************************************
            protected void Page_Load(object sender, EventArgs e)
            {
                      
                //pasta na qual sera arquivada imagens
                Editor.ImageManager.ViewPaths = new string[] { "~/Arquivos/Img" };
                Editor.ImageManager.UploadPaths = new string[] { "~/Arquivos/Img" };
                Editor.ImageManager.DeletePaths = new string[] { "~/Arquivos/Img" };
                Editor.ImageManager.MaxUploadFileSize = 10000000;
                Editor.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);
                    //Set Maximum Width of Image
                    int ImageMaxwidth = 700;
                    // Finds height and width of original image
                    float OriginalHeight = image.Height;
                    float OriginalWidth = image.Width;
                    float Diferenca = 0;
                    // Finds height and width of resized image
                    int NewWidth = 0;
                    int NewHeight = 0;
                    if (OriginalWidth > ImageMaxwidth) // a largura é maior que a máxima??
                    {
                       Diferenca=(OriginalWidth - ImageMaxwidth); //acha a difereça
                       Diferenca=(Diferenca / OriginalWidth); //calcula percentual
                       NewWidth = ImageMaxwidth; //atribui a largura máxima
                       NewHeight = (int)(OriginalHeight -(OriginalHeight * Diferenca)); //reduz altura proporcional a redução da largura
                     }
                    else
                    {
                        NewHeight = (int)OriginalHeight;
                        NewWidth = (int)OriginalWidth;
                    }
                    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.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.DrawImage(sourceImage, 0, 0, newSize.Width, newSize.Height);
                    g.Dispose();
                    return (System.Drawing.Image)bitmap;
                }
     
            }
    //*************************************************************************************************************************
Back to Top