Click here to Skip to main content
15,919,358 members
Articles / Web Development / ASP.NET
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.56/5 (5 votes)
22 Oct 2014CPOL1 min read 15.4K   183   6   1
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.

HTML
<%@ 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.

C#
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

Image 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Member 1090330723-Oct-14 10:34
Member 1090330723-Oct-14 10:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.