Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize image width in c# but not the height

Tags:

c#

image

razor

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

like image 832
Sheldon Avatar asked Feb 01 '26 19:02

Sheldon


2 Answers

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);
like image 162
gilly3 Avatar answered Feb 03 '26 09:02

gilly3


Solution applicable for Winform


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);
like image 34
Parimal Raj Avatar answered Feb 03 '26 08:02

Parimal Raj