An easy problem, but for some reason I just can't figure this out today.
I need to resize an image to the maximum possible size that will fit in a bounding box while maintaining the aspect ratio.
Basicly I'm looking for the code to fill in this function:
void CalcNewDimensions(ref int w, ref int h, int MaxWidth, int MaxHeight);
Where w & h are the original height and width (in) and the new height and width (out) and MaxWidth and MaxHeight define the bounding box that the image must fit in.
To Resize the Bounding Box Connect a Viewer to the AdjBBox node, so you can see the effect of your changes. 3. In the AdjBBox controls, adjust the Add Pixels slider to increase or decrease the size of the bounding box. By default, 25 pixels are added to the edges of the bounding box.
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.
You can drag the selected object to move it. You can scale or resize the selection by using any of the eight handles that appear on the perimeter of the bounding box. Holding down the Shift key while resizing constrains proportion.
Using object-fit When you add an image to a page using the HTML <img> element, the image will maintain the size and aspect ratio of the image file, or that of any HTML width or height attributes. Sometimes you would like the image to completely fill the box that you have placed it in.
Find which is smaller: MaxWidth / w
or MaxHeight / h
Then multiply w
and h
by that number
Explanation:
You need to find the scaling factor which makes the image fit.
To find the scaling factor, s
, for the width, then s
must be such that: s * w = MaxWidth
. Therefore, the scaling factor is MaxWidth / w
.
Similarly for height.
The one that requires the most scaling (smaller s
) is the factor by which you must scale the whole image.
Based on Eric's suggestion I'd do something like this:
private static Size ExpandToBound(Size image, Size boundingBox) { double widthScale = 0, heightScale = 0; if (image.Width != 0) widthScale = (double)boundingBox.Width / (double)image.Width; if (image.Height != 0) heightScale = (double)boundingBox.Height / (double)image.Height; double scale = Math.Min(widthScale, heightScale); Size result = new Size((int)(image.Width * scale), (int)(image.Height * scale)); return result; }
I might have gone a bit overboard on the casts, but I was just trying to preserve precision in the calculations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With