65.9K
CodeProject is changing. Read more.
Home

Adding Image in the Image Control without Stretching/Compressing the Image

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.56/5 (5 votes)

Oct 22, 2014

CPOL

1 min read

viewsIcon

15541

downloadIcon

183

Adding Image in the Container without stretching/compressing the Image

Introduction

If you want to add image in a container (which has custom size) without stretching the image, this code will be useful for you.

Generally, after adding the image, stretch image appears because image takes the container size.

So many cases are generated for Image Size which are given in the below table like “Image size is smaller than Container size”, “Image size is larger than Container size”, “Image width is larger than Container width size but Image height is smaller than Container height size”, “Image size is just double,triple... than Container size”, “Image size is equal than Container size” and so on.......

 Handled in code  Container Width   Original Image Width   Container Height   Original Image Height 
 (if case position)
 Case 1:      2           149      <           170                   211      <      300       
 Case 2:      1           149      <           188                   211      >      179
 Case 3:      1           149      <           300                   211      <      300    
 Case 4:      1           149      <           211                   211      =      211
 Case 5:      3           149      >           138                   211      >      112
 Case 6:      2           149      >           120                   211      <      260
 Case 7:      2           149      >           128                   211      =      211
 Case 8:      1           149      =           149                   211      >      143
 Case 9:      2           149      =           149                   211      <      300    
 Case 10:     1           149      =           149                   211      =      211
 Case 11:     1           149      *2          298                   211      *2     422     

Default.aspx Page

There are 3 image controls in Default.aspx page.”imgContainer” for Original Image, “imgFirstContainer” image control has custom size (149,211) which contains Stretched/Compressed Image due to custom size of Image Container and “imgSecondContainer” image control contains the image without stretching due to applying the “GetImageSizeAndLocation” function.

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
    Inherits="NewImageSizeForImageControl._Default" %>
<html>
<head>
   <title>Image without Stretching/Compressing</title>
</head>
<body>    
    <div>
        <image id="imgContainer" runat="server" src="Image/photo.jpg"/>
         Original Image(Size : 200px,150px)
    </div>
    <hr/>
    <div>
        <image id="imgFirstContainer" runat="server" style="width: 149px; height: 211px" /> 
        Stretched/Compressed Image(Size : Taking Container Size(149px,211px))
    </div>
    <hr/>
    <div>
        <image id="imgSecondContainer" runat="server" style="width: 149px; height: 211px;" />
        Image after applied function(Size : (149px,111px) In Ratio of Container Size)
    </div>
</body>
</html>

Code Behind

In this code, you add the image without stretching and you can also centralize the image according to the original size of container.

After calling the GetImageSizeAndLocation method, you will get new width and new height of image container through intNewWidth and intNewHeight.

For centralizing the image, you have to add intLeft for left/right margin of image and add intTop for top/bottom margin of image.

using System;

namespace NewImageSizeForImageControl
{
    public partial class _Default : System.Web.UI.Page
    {
        //Page Load Method
        protected void Page_Load(object sender, EventArgs e)
        {
            int intLeft=0;
            int intTop=0;
            int intNewWidth=0;
            int intNewHeight=0;
            string strImagePath = "Image\\photo.jpg";

            if (!IsPostBack)
            {
                imgFirstContainer.Attributes.Add("src", strImagePath);

                //For getting the new Width & new Height of Image Container
                GetImageSizeAndLocation(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + 
                strImagePath, ref intLeft, ref intTop, ref intNewWidth, ref  intNewHeight);
                
                //New Size of Image Container according to Image Size
                imgSecondContainer.Style.Add("width", intNewWidth.ToString() + "px");
                imgSecondContainer.Style.Add("height", intNewHeight.ToString() + "px");

                //Centeralize the image
                imgSecondContainer.Style.Add("margin-left", intLeft.ToString() + "px");
                imgSecondContainer.Style.Add("margin-right", intLeft.ToString() + "px");
                imgSecondContainer.Style.Add("margin-top", intTop.ToString() + "px");
                imgSecondContainer.Style.Add("margin-bottom", intTop.ToString() + "px");

                imgSecondContainer.Attributes.Add("src", strImagePath);
            }
        }

        /// <summary>
        /// For getting the new Width & new Height of image according to container size(149*211) and Left & Top  
            of image to centralized
        /// </summary>
        /// <param name="strImagePath">Image Path</param>
        /// <param name="intLeft">Left Position for Centeralize the image</param>
        /// <param name="intTop">Top Position for Centeralize the image</param>
        /// <param name="intNewWidth">New Width of Container</param>
        /// <param name="intNewHeight">New Height of Container</param>
        private void GetImageSizeAndLocation(string strImagePath, ref int intLeft, ref int intTop, ref int 
        intNewWidth, ref int intNewHeight)
        {
            float floatRatioWidth = 0;
            float floatRatioHeight = 0;
            float floatImageWidth = 0;
            float floatImageHeight = 0;
            float floatContainerWidth = 149; //Container Size(Custom Size)
            float floatContainerHeight = 211;

            System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(strImagePath);

            floatImageWidth = sourceImage.Width;
            floatImageHeight = sourceImage.Height;

            //Getting the Width Ratio and Height Ratio 
            floatRatioWidth = floatContainerWidth / floatImageWidth;
            floatRatioHeight = floatContainerHeight / floatImageHeight;

            if ((floatImageWidth > floatContainerWidth && floatImageHeight > floatContainerHeight && 
            floatRatioWidth <= floatRatioHeight)
               || (floatImageWidth >= floatContainerWidth && floatImageHeight <= floatContainerHeight))
            {
                intNewWidth = (int)(floatImageWidth * floatRatioWidth);
                intNewHeight = (int)(floatImageHeight * floatRatioWidth);
            }
            else if ((floatImageWidth > floatContainerWidth && floatImageHeight > floatContainerHeight && 
            floatRatioWidth > floatRatioHeight)
                   || (floatImageHeight >= floatContainerHeight && floatImageWidth <= floatContainerWidth))
            {
                intNewHeight = (int)(floatImageHeight * floatRatioHeight);
                intNewWidth = (int)(floatImageWidth * floatRatioHeight);
            }
            else
            {
                intNewWidth = (int)floatImageWidth;
                intNewHeight = (int)floatImageHeight;
            }

            intLeft = (int)(floatContainerWidth - intNewWidth) / 2;
            intTop = (int)(floatContainerHeight - intNewHeight) / 2;
        }
    }
}

You get the 4 intLeft, intTop, intNewWidth, intNewHeight variables after calling the GetImageSizeAndLocation function/method.

intNewWidth and intNewHeight variables for new width and height of image container.

intLeft, intTop variables for centralizing the image according to original Image Container Size (149, 211).

Output Screen