简体   繁体   中英

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/ . 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.

Doing image processing from ASP.NET is very tricky. You really shouldn't do it unless you have a strong Win/C++ background. .NET does not garbage collect System.Drawing instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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