Jump to content

Resize to fit within rectangle


tibberous

Recommended Posts

I want to resize an image to fit within a rectangle.

 

Lets say my rectangle is 400 wide and 200 tall.

 

My image is 300x300.

 

It should take, and make the rectangle 200 tall, then scale the width accordingly.

 

I wrote a function a while back that resizes inside a square, but that was a little easier, since you know to constrain by height if height is greater than width, and to constrain by width if width is greater than height.

 

	$w = $stats[0];
	$h = $stats[1];

	if($dim){ // constrain image
		if($w > $h){
			$h = ($h / $w) * $dim;
			$w = $dim;
		} else {
			$w = ($w / $h) * $dim;
			$h = $dim;
		}
	}

 

Thats my code to constrain inside a box. It gets the starting h and w from $stats, which is loaded from getimagesize. Then it sets a new h and w based on dim, which is the size of the box.

 

The new version will need dimW and dimH, instead of just dim.

 

Can anyone help me out?

Link to comment
https://forums.phpfreaks.com/topic/227129-resize-to-fit-within-rectangle/
Share on other sites

Got it:

 

$dimW = $dim[0];

$dimH = $dim[1];

 

if( ($w*$dimW) <= ($h*$dimH) ){

$h = ($h / $w) * $dimW;

$w = $dimW;

} else {

$w = ($w / $h) * $dimH;

$h = $dimH;

}

 

Trick with shit like this is to draw out the problem and know what your final values are going to be.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.