简体   繁体   English

C#调整图像大小并使其适合正方形,同时保持宽高比

[英]c# resize image and fit it into the square while preserving aspect ratio

I am doing little work for my website and I would like to auto-resize my images.. But not only auto-resize, but keep them proportional, even if I resize their width or height. 我为网站做的工作很少,我想自动调整图像的大小。但是,不仅要自动调整大小,还要保持它们成比例,即使我调整其宽度或高度也是如此。 I want to add additional white borders to compensate for new space. 我想添加其他白色边框以补偿新空间。

I have never done any image work in the past, how should I approach this? 我过去从未做过任何图像工作,应该如何处理?

Calculate the height as if the width would fit, then check that against the height of the container. 计算宽度是否合适,然后根据容器的高度检查高度。 If it's higher, then calculate the width to make the height fit: 如果更高,则计算宽度以使高度合适:

newHeight = oldHeight * containerWidth / oldWidth;
if (newHeight <= containerHeight) {
  newWidth = containerWidth;
} else {
  newWidth = oldWidth * containerHeight / oldHeight;
  newHeight = containerHeight;
}

Now you can calculate where to place the image to center it: 现在,您可以计算将图像放置在中心的位置:

x = (containerWidth - newWidth) / 2;
y = (containerHeight - newHeight) / 2;

If you're talking about single-source imaging, where you upload a primary image and request versions of it via a querystring, then I can help. 如果您谈论的是单源图像处理,即在其中上传主图像并通过查询字符串请求其原始版本,那么我可以为您提供帮助。

I'm the author of http://imageresizing.net/ . 我是http://imageresizing.net/的作者。 It's an open-source library funded by add-on plugins. 这是一个由附加插件资助的开源库。

The functionality you want is included in the free core - just install and add ?width=100&height=100 to any image URL. 您所需的功能已包含在免费内核中-只需安装?width = 100&height = 100并将其添加到任何图像URL。

Doing image processing from ASP.NET is very tricky. 从ASP.NET进行图像处理非常棘手。 You really shouldn't do it unless you have a strong Win/C++ background. 除非您具有强大的Win / C ++背景,否则您实际上不应该这样做。 .NET does not garbage collect System.Drawing instances. .NET不会垃圾收集System.Drawing实例。

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

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