ColdFusion & .NET: Resizing the Height of an Image

After last week's post on resizing images in ColdFusion and .NET based on width, someone contacted me and asked me about resizing the image based on height.  So below is how you accomplish that in ColdFusion and in .NET.

First in ColdFusion:

<code lang="cfm[lines]"><cfimage action="resize" destination="#resizedFile#" height="250" overwrite="yes" source="#sourceFile#" width=""></cfimage>

The .NET function is very similar to the function we covered last week about resizing based on width.  The only difference lies in lines of code where it's computing the sizes.

<code lang="csharp[lines]">static void ResizeImageByHeight(string orgName, string resizeName, int resizeHeight)<br></br>  
        {<br></br>
            String src = orgName;<br></br>
            String dest = resizeName;<br></br>
            int thumbHeight = resizeHeight;```

 //Get the source image to a System.Drawing.Image object  
 System.Drawing.Image image = System.Drawing.Image.FromFile(src);

 //Create a System.Drawing.Bitmap with the desired width and height of the thumbnail.  
 int srcWidth = image.Width;  
 int srcHeight = image.Height;

 Decimal sizeRatio = ((Decimal)srcWidth / srcHeight);  
 int thumbWidth = Decimal.ToInt32(sizeRatio * thumbHeight);  
 Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);

 //Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image  
 System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);

 //Set the System.Drawing.Graphics object property SmoothingMode to HighQuality  
 gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

 //Set the System.Drawing.Graphics object property CompositingQuality to HighQuality  
 gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

 //Set the System.Drawing.Graphics object property InterpolationMode to High  
 gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

 //Draw the original image into the target Graphics object scaling to the desired width and height  
 System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);  
 gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);

 //Save to destination file  
 bmp.Save(dest);

 //dispose / release resources  
 bmp.Dispose();  
 image.Dispose();  
 }

I did forget to mention in last week's post, the .NET classes you need to import for the .NET code to run.  Those are:

using System.IO;


using System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;```

Comments

comments powered by Disqus