0

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Andrew
  • 7,619
  • 13
  • 63
  • 117
  • What have you tried so far? There are plenty of existing image resizing questions on here to get you started, e.g. my answer here: http://stackoverflow.com/questions/10106792/resize-image-by-pixel-amount/10109195#10109195 – Widor May 25 '12 at 16:53
  • Your tagged as winforms, but you are saying it's for your website. – General Grey May 25 '12 at 18:08

2 Answers2

8

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;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • So how to centre the image/ how to use it in the img tag? @guffa – nickornotto Sep 09 '15 at 17:37
  • @user1611620: There are many ways. You can for example use padding or margin to place an image tag according to the coordinates, or absolute positioning. – Guffa Sep 09 '15 at 19:32
  • @nickornotto you can center a image simply by few lines of CSS. On a rough note it would be like: Container/parent div of image should be having 'position' relative, then img tag I assume to be child of that parent div. For img css make it position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); And you will be having image horizontally and vertically centered without any padding or margin to adjust by your self. It will manage its own to make it self center despite the size of parent div. – Tarik1322 Jul 23 '20 at 07:48
-1

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.

Lilith River
  • 16,204
  • 2
  • 44
  • 76