Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scale image to completely fill bounding box

For instance, if I need to fill a bounding box that is 100px wide by 50px tall, the following input images would have the following behavior:

  1. 200w x 200h gets scaled down 50% and 25% gets chopped off the top and bottom.

  2. 200w x 100h gets scaled down 50% with no cropping.

  3. 100w x 200h gets is not scaled, but 75px get chopped off top and bottom.

This seems like it'd be a common resizing function, but I haven't been able to track down an example of the algorithm.

Will accept answer in any language including pseudo code. A link to a page with the answer is great too!

like image 863
Larsenal Avatar asked Mar 06 '09 03:03

Larsenal


People also ask

How do I scale an image to fit CSS?

The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container. This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".

How do I make an image occupy a whole div?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.

How do you change the size of a bounding box?

Expand General and size. Click within the size value field. Select the width value and change the size. Press Enter to save the change to the bounding box width.

How do I resize a bounding box in Photoshop?

With the white square layer selected, click on the Edit menu, and select Transform>Scale. A bounding box with corner and side handles will appear around the white box. To quickly scale the box, click and drag any handle and the size of the box will change proportionally.


1 Answers

What you're asking for is pretty easy. Calculate the different scaling factors for the width and the height, then pick the larger one for your actual scale factor. Multiply your input size by the scale, and crop whichever one comes out too large.

scale = max(maxwidth/oldwidth, maxheight/oldheight)
scaledwidth = oldwidth * scale
scaledheight = oldheight * scale
if scaledheight > maxheight:
    croptop = (scaledheight - maxheight) / 2
    cropbottom = (scaledheight - maxheight) - croptop
if scaledwidth > maxwidth:
    cropleft = (scaledwidth - maxwidth) / 2
    cropright = (scaledwidth - maxwidth) - cropleft
like image 127
Mark Ransom Avatar answered Sep 28 '22 07:09

Mark Ransom