How do you resize the width of a image in C# without resizing the height using image.resize()
When I do it this way:
image.Resize(width: 800, preserveAspectRatio: true,preventEnlarge:true);
This is the full code:
var imagePath = "";
var newFileName = "";
var imageThumbPath = "";
WebImage image = null;
image = WebImage.GetImageFromRequest();
if (image != null)
{
newFileName = Path.GetFileName(image.FileName);
imagePath = @"pages/"+newFileName;
image.Resize(width:800, preserveAspectRatio:true, preventEnlarge:true);
image.Save(@"~/images/" + imagePath);
imageThumbPath = @"pages/thumbnail/"+newFileName;
image.Resize(width: 150, height:150, preserveAspectRatio:true, preventEnlarge:true);
image.Save(@"~/images/" + imageThumbPath);
}
I get this error message:
No overload for method 'Resize' takes 3 arguments
The documentation is garbage, so I peeked at the source code. The logic they are using is to look at the values passed for height and width and compute aspect ratios for each comparing the new value to the current value. Whichever value (height or width) has the greater aspect ratio gets its value computed from the other value. Here's the relevant snippet:
double hRatio = (height * 100.0) / image.Height;
double wRatio = (width * 100.0) / image.Width;
if (hRatio > wRatio)
{
height = (int)Math.Round((wRatio * image.Height) / 100);
}
else if (hRatio < wRatio)
{
width = (int)Math.Round((hRatio * image.Width) / 100);
}
So, what that means is that, if you don't want to compute the height value yourself, just pass in a height value that is very large.
image.Resize(800, 100000, true, true);
This will cause hRatio to be larger than wRatio and then height will be computed based on width.
Since you have preventEnlarge set to true, you could just pass image.Height in.
image.Resize(800, image.Height, true, true);
Of course, it's not difficult to just compute height yourself:
int width = 800;
int height = (int)Math.Round(((width * 1.0) / image.Width) * image.Height);
image.Resize(width, height, false, true);
Using this function :
public static Image ScaleImage(Image image, int maxWidth)
{
var newImage = new Bitmap(newWidth, image.Height);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, image.Height);
return newImage;
}
Usage :
Image resized_image = ScaleImage(image, 800);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With