Andrew
Andrew

Reputation: 7768

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?

Upvotes: 0

Views: 2456

Answers (2)

Lilith River
Lilith River

Reputation: 16468

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.

Upvotes: -1

Guffa
Guffa

Reputation: 700152

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;

Upvotes: 8

Related Questions