简体   繁体   English

调整c#中的图像宽度,但不调整高度

[英]Resize image width in c# but not the height

How do you resize the width of a image in C# without resizing the height using image.resize() 如何使用image.resize()调整C#中图像的宽度而不调整高度

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 方法'Resize'没有重载需要3个参数

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 . 这将导致hRatio大于wRatio ,然后将根据width计算height

Since you have preventEnlarge set to true , you could just pass image.Height in. 由于您将preventEnlarge设置为true ,因此您可以直接传递image.Height

image.Resize(800, image.Height, true, true);

Of course, it's not difficult to just compute height yourself: 当然,自己计算height并不困难:

int width = 800;
int height = (int)Math.Round(((width * 1.0) / image.Width) * image.Height);
image.Resize(width, height, false, true);

Solution applicable for Winform 适用于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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM