Monday, July 25, 2005

How to resize images dynamically

How many times did you need to resize an image in an image editor to standardize the image sizes on your web site?

How many times dod you need to create thumbnails of the images?

How about adding a border ?

If it is part of your daily work, smile :)

Here is how you do it in ASP.NET : Copy the code below into the Load event handler in an aspx page, and set the src of your image to this aspx page with the relevant parameters...

Don't forget to reference System.Drawing.Drawing2D and system.Drawing.Imaging in your code.



Copy below the line
--------------
public void Page_Load(object sender, System.EventArgs e){
string myImg = Request["i"];
if(myImg == null myImg == "") { myImg = "defaultimage.jpg"; }
string myBorder = Request["b"];
if(myBorder == null myBorder == "") { myBorder = "border.gif"; }
Bitmap original = new Bitmap(Server.MapPath(@"~/images/" + myImg),true );
int mySize = original.Size.Width ;
Bitmap border=new Bitmap(Server.MapPath(@"~/images/" + myBorder), true);
Bitmap outputbitmap = new Bitmap(mySize, mySize);
// using statement makes sure that the graphics object is properly disposed
using(Graphics g = Graphics.FromImage(outputbitmap))
{
//Make it high Quality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode= SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(original, new Rectangle(0,0,mySize, mySize ));
border.MakeTransparent(Color.Black );
g.DrawImage(border, new Rectangle(0,0,mySize, mySize));

}
//' get the requested size,the example is a square
if(Request.QueryString["s"]!= null && Request.QueryString["s"]!= "" )
{ mySize = int.Parse(Request.QueryString["s"]); }
System.Drawing.Image outputimage =
outputbitmap.GetThumbnailImage( mySize, mySize, null, new IntPtr());
Response.Clear();
// set the mime type
Response.ContentType="image/Jpeg";
//' send the image to the viewer
outputimage.Save(Response.OutputStream, ImageFormat.Jpeg);
}
--------

0 Comments:

Post a Comment

<< Home