Reputation: 1999
I have an image control in my webform. I set its width 100px and height 100px. but if someone upload an image of ratio 100 * 120. I want it crop or resize and set 100 * 100. I tried to set max width but not worked , I tried bitmap method with code
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string filename = FileUpload1.FileName;
string directory = Server.MapPath("~/");
Bitmap originalBMP = new Bitmap(FileUpload1.FileContent);
float origWidth = originalBMP.Width;
float origHeight = originalBMP.Height;
float sngRatio = origWidth / origHeight;
float newWidth = 100;
float newHeight = newWidth / sngRatio;
Bitmap newBMP = new Bitmap(originalBMP,Convert.ToInt32(newWidth),Convert.ToInt32(newHeight));
Graphics oGraphics = Graphics.FromImage(newBMP);
oGraphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
oGraphics.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
newBMP.Save(directory + filename);
originalBMP = null;
newBMP = null;
oGraphics = null;
Label1.Text = "File <b style='color: red;'>" + filename + "<</b> uploaded.";
Image1.ImageUrl = @"~/" + filename;
}
else
{
Label1.Text = "No file uploaded!";
}
}
it worked but it save the resized image in directery I want to save original image in directory and display the resize image in image control.
Upvotes: 1
Views: 3754
Reputation: 4320
Check out Web Image Resize handler on codeplex : http://webimageresizer.codeplex.com/
It is a custom handler to process images.
Sample urls Taken from the codeplex project's home page
// Returns the image mapping to /bla.jpg resized to width of 100 pixels preserving aspect relative to height /ImageHandler.ashx?src=/bla.jpg&width=100
// Returns the image mapping to /bla.jpg resized to height of 100 pixels preserving aspect relative to width /ImageHandler.ashx?src=/bla.jpg&height=100
// Returns the image mapping to /bla.jpg resized to width 100 pixels and a height of 50 pixels /ImageHandler.ashx?src=/bla.jpg&width=100&height=50
Another option is to use http://imageresizing.net/
The benefit is that it registers a handler to handle images transparently, meaning, that you only add querystring variables to your original image url to manipulate the image.
Sample urls
/images/bla.jpg?h=100&w=100
Upvotes: 1