Monday, June 01, 2009

Kentico CMS 4.0 and Bounded Box Image Resizing

This article has code specifically for Kentico CMS 4.0 and can be used in a scenario where you have an image’s dimensions and want to ensure that the image fits into a known bounded box.

With Kentico CMS you retrieve images using a call to a handler at /CMSPages/GetFile.aspx. That page accepts parameters Height, Width and MaxSideSize. Height and Width can be fixed and specifying one and not the other will retain aspect ratio. MaxSideSize allows a single value to bound the height and width.

However, if you have a given bounded box on the page (e.g. say a 400 * 300 space) and you want to make sure an image fits inside that space whilst retaining aspect ratio there is no way to do this.

I’ve emailed this code to the Kentico support team to allow MaxHeight and MaxWidth properties so that we can do this. In the meantime this hack/fix within GetFile.aspx.cs code behind file will allow you to supply negative values for height and width which then act as a bounding box!

// HACK - Interpret MaxHeight and MaxWidth via negative Height and Width values (line 599)
if (this.Height < 0 || this.Width < 0)
    ApplyBoundingBox(atInfo.AttachmentImageHeight, atInfo.AttachmentImageWidth);

/// <summary>
   /// Custom Hack to interpret negative height and width values as setting bounding box
   /// </summary>
   private void ApplyBoundingBox(int imageHeight, int imageWidth)
   {

       if (this.Height >= 0 && this.Width >= 0)
           return;

       int maxHeight = 0;
       int maxWidth = 0;
       float ratio = 0;

       if (this.Height < 0)
       {
           maxHeight = this.Height * -1;
           this.Height = imageHeight;
       }

       if (this.Width < 0)
       {    
           maxWidth = this.Width * -1;
           this.Width = imageWidth;
       }

       if (maxHeight > 0 && this.Height > maxHeight)
       {
           ratio = (float)this.Height / (float)maxHeight;
           this.Height = maxHeight;          
           this.Width = (int)((float)this.Width / (float)ratio);
       }

       if (maxWidth > 0 && this.Width > maxWidth)
       { 
           ratio = (float)this.Width / (float)maxWidth;
           this.Width = maxWidth;
           this.Height = (int)((float)this.Height / (float)ratio);
       }

   }

Comments are closed.