Thursday, April 26, 2012

Resizing image size without distorting the image

In my current project, the images needs to be displayed without any distortion – no bleed, no stretch .. J

Considering the scenario, setting any value to the img width or height would not solve the purpose since different images were uploaded with different sizes.  Thus took the decision to manipulate the pixels. The primary logic to get the original image size, get the ratio factor and then reduce or enlarge the image. Below is the whole code stub, need to pass the parameters to get new size. Only need to add using System.Drawing; – simply copy and use….

 

#region Get the Resized Image Dimentions

        /// <summary>

        /// Returns the resized image dimentions without distorting the image

        /// </summary>

        /// <param name="OriginalWidth"></param>

        /// <param name="OriginalHeight"></param>

        /// <param name="MaxWidth"></param>

        /// <param name="MaxHeight"></param>

        /// <returns></returns>

        public static Size GetResizedImageDimensions(int OriginalWidth, int OriginalHeight, int IntendedMaxWidth, int IntendedMaxHeight)

        {

            Size NewSize = new Size();

            try

            {

                //Check if the original image dimentions are greater than the specidied ones

                if (OriginalWidth > IntendedMaxWidth || OriginalHeight > IntendedMaxHeight)

                {

                    //Get the value for ratio

                    double widthRatio = (double)OriginalWidth / (double)IntendedMaxWidth;

                    double heightRatio = (double)OriginalHeight / (double)IntendedMaxHeight;

                    //determin which ration to use

                    double ratio = Math.Max(widthRatio, heightRatio);

                    //getting the new image dimentions

                    int newWidth = (int)(OriginalWidth / ratio);

                    int newHeight = (int)(OriginalHeight / ratio);

                    //NewSize = new Size(newWidth, newHeight);

                    NewSize.Height = newHeight;

                    NewSize.Width = newWidth;

                }

                else

                {

                    //NewSize = new Size(OriginalWidth, OriginalHeight);

                    NewSize.Height = (int)OriginalHeight;

                    NewSize.Width = (int)OriginalWidth;

                }

            }

            catch (Exception ex)

            {

                PortalLog.LogString("Exception occrured in Image Resize Method" + ex.Message);

            }

            return NewSize;

        }

        #endregion

 

Thanks for reading..

If you have a more elegant solution/suggestion – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

 

No comments:

Post a Comment