Monday, August 10, 2009

Resize Image With Perfect Ratio with [Height x Width] in Asp.Net

Use Namespace
================
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

Code Behind
============

System.Drawing.Image img;
img = System.Drawing.Image.FromFile(cStrTextFileName);

Bitmap bmp = new System.Drawing.Bitmap(img);

System.Drawing.Image.GetThumbnailImageAbort imgCallBack = new System.Drawing.Image.GetThumbnailImageAbort(CallBackMethod);

//System.Drawing.Bitmap bmpThumbnail = ((Bitmap)bmp.GetThumbnailImage(62, 48, imgCallBack, IntPtr.Zero));

/******************/
int[] HWRation = ResizeImageWithRatio(img, 120, 60);
/******************/

System.Drawing.Bitmap bmpThumbnail = ((Bitmap)bmp.GetThumbnailImage(HWRation[0], HWRation[1], imgCallBack, IntPtr.Zero));

//System.Drawing.Bitmap bmpThumbnail = ((Bitmap)bmp.GetThumbnailImage(120, 60, imgCallBack, IntPtr.Zero));
bmpThumbnail.SetResolution(img.HorizontalResolution, img.VerticalResolution);
img.Dispose();

bmpThumbnail.Save(Server.MapPath("images/logo/") + Session["userid"].ToString() + strExtension);

imgImage.Src = "images/logo/" + Session["userid"].ToString() + strExtension;

// Upload New File..
// fileImage.PostedFile.SaveAs(MapPath("logo/") + Session["userid"].ToString() + strExtension);

Image Resize Function
=====================
int[] ResizeImageWithRatio(System.Drawing.Image img, int MaxWidth, int MaxHeight)
{
int[] newHeightWidth = new int[2];

if (img.Width > MaxWidth || img.Height > MaxHeight)
{
double widthRatio = (double)img.Width / (double)MaxWidth;
double heightRatio = (double)img.Height / (double)MaxHeight;
double ratio = Math.Max(widthRatio, heightRatio);
int newWidth = (int)(img.Width / ratio);
int newHeight = (int)(img.Height / ratio);

newHeightWidth[0] = newWidth;
newHeightWidth[1] = newHeight;

}
else
{
newHeightWidth[0] = img.Width;
newHeightWidth[1] = img.Height;
}
return newHeightWidth;
}

public bool CallBackMethod()
{
return false;
}

No comments: