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)

 

Using in HtmlDocument Class in Asp.net/SharePoint -Visual Web Part

Using in  HtmlDocument Class in Asp.net/SharePoint -Visual Web Part

 

I faced this situation where I have to read a HTML from a string, get the image tag manipulate and create a new image tag and return.

 

I tried to use HtmlDocument object from System.Window.Form, but it caused threading issue, after few googling got reference to the HTMLAgilityPack

Downloaded and added to my project. Below is the usage.

 

#region Get Image From HTML Text

        /// <summary>

        /// Get image tag from html text

        /// </summary>

        /// <param name="strHTML"></param>

        /// <returns></returns>

        public static string GetImageFromHTMLText(string strHTML)

        {

            //local varibales to store the image attributes

            string strSrc = string.Empty;

            string strWidth = string.Empty;

            string strHeight = string.Empty;

            string strAlt = string.Empty;

            string strFinalImageText = string.Empty;

            try

            {

                //Using HTML Agility Pack downloaded from Codeplex - htmlagilitypack.codeplex.com

                //reduces the thread handling required if we use System.Windows.Form for HtmlDocument object

                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlDocument();

                //Loads the html

                htmlDoc.LoadHtml(strHTML);

                //foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//img[@src]"))

                //loop thru the image tags - xsl for image -

                foreach (HtmlNode image in htmlDoc.DocumentNode.SelectNodes("//img"))

                {

                    HtmlAttributeCollection attCollection = image.Attributes;

                    strSrc = image.GetAttributeValue("src", null);

                    strWidth = (image.GetAttributeValue("width", null) == null) ? "100" : image.GetAttributeValue("width", null);

                    strHeight = (image.GetAttributeValue("height", null) == null) ? "100" : image.GetAttributeValue("height", null);

                    strAlt = image.GetAttributeValue("alt", null);

                }

                               

                //Get the intended size - here as 200px

                Size NewSize = GetResizedImageDimensions(int.Parse(strWidth), int.Parse(strHeight), 200, 160);

                //Creating the new image html string

                strFinalImageText = string.Format(@"<img width='{0}' height='{1}' alt='{2}', src='{3}'/>", NewSize.Width, NewSize.Height, strAlt, strSrc);

            }

            catch (Exception ex)

            {

                PortalLog.LogString("Exception occrured in Get Image innter HTML" + ex.Message);

            }

            return strFinalImageText;

        }

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

Thursday, April 19, 2012

Custom Paging with Data List in SharePoint

 

In this article I have explained about how to create custom paging in Datalist control.

 

I will directly jump to the code. I have created a custom Visual WebPart with this Datalist to show some images stored in a image library.

The ascx page

 

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>

<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ImageView_EventsPhotoUserControl.ascx.cs" Inherits="My.SP.VisualWebpart.News.ImageView_EventsPhoto.ImageView_EventsPhotoUserControl" %>

<table border="0" cellpadding="0" cellspacing="0" style="width: 100%">

    <tr class="ContentADP">

        <td align="left" style="font-size: 22px; width: 50%" class="NewsHeading_LV2">

            Events Photos

        </td>

        <td style="width: 50%; text-align: right; padding-right: 10px">

            <asp:Button ID="btnPrev" runat="server" Text="<<" OnClick="btnPrev_Click" /><asp:Label

                ID="lblCurrentPage" runat="server" Text=""></asp:Label><asp:Button ID="btnNext" runat="server"

                    Text=">>" OnClick="btnNext_Click" />

        </td>

    </tr>   

</table>

<asp:DataList ID="dlImages" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"

    OnItemDataBound="dlImages_ItemDataBound">

    <ItemTemplate>

        <table id="Table1" cellpadding="0" border="1" cellspacing="1">

            <tr>

                <td width="150px" style="height: 150px">

                    <asp:Image ID="imgProject" runat="server" ImageUrl='<%# Eval("RequiredField") %>'

                        ToolTip='<%# Eval("NameOrTitle") %>' />

                </td>

        </table>

    </ItemTemplate>

</asp:DataList>

 

 

 

Next is the Code behind file

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Data;

using Microsoft.SharePoint;

using Microsoft.Office.Server.Diagnostics;

 

namespace My.SP.VisualWebpart.News.ImageView_EventsPhoto

{

    public partial class ImageView_EventsPhotoUserControl : UserControl

    {

        PagedDataSource pagedData = new PagedDataSource();

        public int currentPage

        {

            get

            {

                object o = this.ViewState["_currentPage"];

                if (o == null)

                    return 0;

                else

                    return (int)o;

            }

            set

            {

                this.ViewState["_currentPage"] = value;

            }

        }

 

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                try

                {

                    BindImages();

                }

                catch (Exception ex)

                {

                    Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception Occured in ListImage web part" + ex.Message);

                    throw new SPException("Check Image view web part");

                    Response.Write(ex.ToString());

                }

            }

        }

 

        protected void BindImages()

        {

            try

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

                {

                    SPSite elevatedSite = new SPSite(SPContext.Current.Site.Url);

                    SPWeb elevatedWeb = elevatedSite.OpenWeb("/news");

                    SPList spListDocumentLib = elevatedWeb.Lists["EventsPhoto"];

                    DataTable dtItems = spListDocumentLib.Items.GetDataTable();

                    if (dtItems != null && dtItems.Rows.Count > 0)

                    {

                        pagedData.DataSource = dtItems.DefaultView;

                        pagedData.AllowPaging = true;

                        pagedData.PageSize = 12;

                        pagedData.CurrentPageIndex = currentPage;

                        btnPrev.Enabled = (!pagedData.IsFirstPage);

                        btnNext.Enabled = (!pagedData.IsLastPage);

                        lblCurrentPage.Text = "Page: " + (currentPage + 1).ToString() + " of " + pagedData.PageCount.ToString();

                        dlImages.DataSource = pagedData;

                        dlImages.DataBind();

                    }

                });

            }

            catch (Exception ex)

            {

                Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Exception Occured in ListImage web part" + ex.Message);

                throw new SPException("Check Image view web part");

                //throw ex;

            }

        }

 

        protected void btnPrev_Click(object sender, EventArgs e)

        {

            //Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (CurPage - 1));

            currentPage -= 1;

            BindImages();

        }

 

        protected void btnNext_Click(object sender, EventArgs e)

        {

            //Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (CurPage + 1));

            currentPage += 1;

            BindImages();

        }

 

        protected void dlImages_ItemDataBound(object sender, DataListItemEventArgs e)

        {

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

            {

                string siteurl = SPContext.Current.Site.Url;

                Image imgProject = (Image)e.Item.FindControl("imgProject");

                imgProject.ImageUrl = siteurl + "/news/EventsPhoto/" + imgProject.ToolTip;

                imgProject.Style.Add("width", "200px");

                imgProject.Style.Add("height", "200px");

            }

        }

    }

}

 

 

Thanks for reading..

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

...HaPpY CoDiNg

Partha (Aurum)