tibberous Posted February 9, 2011 Share Posted February 9, 2011 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 More sharing options...
tibberous Posted February 9, 2011 Author Share Posted February 9, 2011 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. Link to comment https://forums.phpfreaks.com/topic/227129-resize-to-fit-within-rectangle/#findComment-1171702 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.