Tuesday, May 26, 2009

Image Resize (on fly thumbnail image generation)

1)web.config


2)Create Folder called images (on application physical path)

3)Create .cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

///


/// Summary description for Lib
///

public class Lib
{
public Lib()
{
//
// TODO: Add constructor logic here
//
}


#region Thumbnail Functions
public bool ThumbnailCallback()
{
return false;
}


private float DeterminePercentageForResize(int height, int width)
{
int highestValue;
if (height > width)
highestValue = height;
else
highestValue = width;

float percent = (float)int.Parse(ConfigurationManager.AppSettings["ThumbSize"].ToString()) / (float)highestValue;

if (percent > 1 && percent != 0)
throw new Exception("Percent cannot be greater than 1 or equal to zero");
else
return percent;
}

private static System.Drawing.Image FixedSize(System.Drawing.Image imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent)) / 2);
}

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.White);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(0, 0, destWidth, destHeight),
new Rectangle(0, 0, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);



grPhoto.Dispose();
return bmPhoto;
}

public bool SaveAsThumbnail(string largeimage)
{
bool status = false;
try
{
string strPathPrefix = ConfigurationManager.AppSettings["UploadPrefix"].ToString();
string strPath = ConfigurationManager.AppSettings["UploadLocation"].ToString();

string strFilename = System.IO.Path.GetFileNameWithoutExtension(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
string strThumbnail = strFilename + "_small.jpg";

int intThumbnailSize = int.Parse(ConfigurationManager.AppSettings["ThumbSize"].ToString());
int intWidth, intHeight;
Bitmap photo;

try
{
photo = new Bitmap(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
}
catch (ArgumentException)
{
throw new HttpException(404, "Photo not found.");
}

if (photo.Width > intThumbnailSize)
{
if (photo.Width > photo.Height)
{
intWidth = intThumbnailSize;
intHeight = photo.Height * intThumbnailSize / photo.Width;
}
else
{
intWidth = photo.Width * intThumbnailSize / photo.Height;
intHeight = intThumbnailSize;
}
}
else
{
intWidth = photo.Width;
intHeight = photo.Height;
}

System.Drawing.Image imgPhotoVert = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
System.Drawing.Image imgPhoto = null;

imgPhoto = FixedSize(imgPhotoVert, intWidth, intHeight);
imgPhoto.Save(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + strThumbnail), ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhotoVert.Dispose();
photo.Dispose();
status = true;

}
catch (Exception ex)
{
//AppLogger.LogError("SaveAsThumbnail(): " + ex.Message, AppLogger.Severity.Error);
ex.Message.ToString();
}

return status;
}

public bool SaveAsImage(string largeimage, int ResizeImageSize, string FileNameRef)
{
bool status = false;
try
{
string strPathPrefix = ConfigurationManager.AppSettings["UploadPrefix"].ToString();
string strPath = ConfigurationManager.AppSettings["UploadLocation"].ToString();

string strFilename = System.IO.Path.GetFileNameWithoutExtension(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
string strThumbnail = strFilename + "_" + FileNameRef + ".jpg";

int intThumbnailSize = ResizeImageSize;
int intWidth, intHeight;
Bitmap photo;

try
{
photo = new Bitmap(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
}
catch (ArgumentException)
{
throw new HttpException(404, "Photo not found.");
}

if (photo.Width > intThumbnailSize)
{
if (photo.Width > photo.Height)
{
intWidth = intThumbnailSize;
intHeight = photo.Height * intThumbnailSize / photo.Width;
}
else
{
intWidth = photo.Width * intThumbnailSize / photo.Height;
intHeight = intThumbnailSize;
}
}
else
{
intWidth = photo.Width;
intHeight = photo.Height;
}

System.Drawing.Image imgPhotoVert = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + largeimage));
System.Drawing.Image imgPhoto = null;

imgPhoto = FixedSize(imgPhotoVert, intWidth, intHeight);
imgPhoto.Save(HttpContext.Current.Server.MapPath(strPathPrefix + strPath + strThumbnail), ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhotoVert.Dispose();
photo.Dispose();
status = true;

}
catch (Exception ex)
{
//AppLogger.LogError("SaveAsImage(): " + ex.Message, AppLogger.Severity.Error);
ex.
}

return status;
}

#endregion
}

4).aspx/ascx


5).aspx.cs/.ascx.cs
on btn_click event
string strpPath = ConfigurationManager.AppSettings["UploadLocation"].ToString();
string strpPathPrefix = ConfigurationManager.AppSettings["UploadPrefix"].ToString();
string extenstion = DateTime.Now.ToString("ddMMyy-HHmm");
string filepath = "", strResizeFilename = "", strFullFilename = "";
bool ResizeImage = false;

Lib objlib = new Lib();

if (fPhotUpload.FileName != "")
{
if (fPhotUpload.HasFile)
{

if (fPhotUpload.HasFile)
{
filepath = extenstion + fPhotUpload.FileName.Replace(" ", "_");
strFullFilename = Server.MapPath(strpPathPrefix + strpPath) + filepath;
fPhotUpload.SaveAs(strFullFilename);
ResizeImage = objlib.SaveAsImage(filepath, Convert.ToInt16(ConfigurationManager.AppSettings["LargeThumbSize"]), "large");
}
if (ResizeImage == true)
{

strResizeFilename = System.IO.Path.GetFileNameWithoutExtension(filepath);
hdnbigimage.Value = strResizeFilename + "_large.jpg";


ResizeImage = false;
ResizeImage = objlib.SaveAsImage(filepath, Convert.ToInt16(ConfigurationManager.AppSettings["ThumbSize"]), "small");

if (ResizeImage == true)
{
strResizeFilename = "";
strResizeFilename = System.IO.Path.GetFileNameWithoutExtension(filepath);
hdnsmallimage.Value = strResizeFilename + "_small.jpg";
}
}
else
{
lblMsg.Text = "Image path cannot be found";
return;
}
}
}

Copyright © 2009 Angel