Friday, July 11, 2008

Image Thumbnail using C#.net

//This is resize function to set image size as you want
resizeimage(imagename); (where imagegname like- image1.jpg)

//this is the image control where you bind the image
img src='MakeThumbnail.aspx?file="imagename" &h=" + h + " &w=" + w + "' height="200" widht="200"


//Resize function (where width of the image will be fix and the hight of the image will be change according to height

public void resizeimage(string image)
{
System.Drawing.Image img;
try
{
string path = Server.MapPath("imagefolder/" + image);
img = System.Drawing.Image.FromFile(path);
}
catch
{

string path = Server.MapPath("imagefolder/no_img_avai.gif");
img = System.Drawing.Image.FromFile(path);
}


h = img.Height;
w = img.Width;
if (w >= 103)
{

int hei = h * 103;
int he = hei / w;
h = he;
w = 103;

}
else
{
int hei = h * 103;
int he = hei / w;
h = he;
}

}



//MAKE ONE ASPX FILE NAME MakeThumbnail.aspx




using System;
using System.IO;
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.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MakeThumbnail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// get the file name -- fall800.jpg
string file = Request.QueryString["file"];
int w = Convert.ToInt32(Request.QueryString["w"]);
int h = Convert.ToInt32(Request.QueryString["h"]);
string filepath = Server.MapPath("imagefolder/" + file.ToString());
// create an image object, using the filename we just retrieved
System.Drawing.Image image = System.Drawing.Image.FromFile(filepath);

// create the actual thumbnail image
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(w, h, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

// make a memory stream to work with the image bytes
MemoryStream imageStream = new MemoryStream();

// put the image into the memory stream
thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

// make byte array the same size as the image
byte[] imageContent = new Byte[imageStream.Length];

// rewind the memory stream
imageStream.Position = 0;

// load the byte array with the image
imageStream.Read(imageContent, 0, (int)imageStream.Length);

// return byte array to caller with image type
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imageContent);
}
public bool ThumbnailCallback()
{
return true;
}
}

1 comment:

Dilip Kumar said...
This comment has been removed by the author.