简体   繁体   中英

Resize image based on aspect ratio php

I want the new height and width to which the image needs to be resized. There are two conditions

  1. Width needs to be around 180px(170-180) but < 180px (uploaded image is always > 180)
  2. Height should be max 180px (uploaded image may or may not be > 180)

If you are writing program for Linux I would recommend using ImageMagick. It is more memory efficient and probably faster than any PHP based method. Almost all servers have it installed. Following code will do the trick.

function resizeTo($source, $dest, $w=180, $h=180) {
    system("convert $source -resize {$w}x{$h} $dest");
}

It will mind the aspect ratio.

Edit:

Sorry for the confusion. I think the following should do what you are looking for. It is not tested and might need a little bit debugging, if you run into trouble I can try and post again.

//accepts and returns point object (having ->x and ->y)
function resizeTo($current, $max) {
   if($current->x <= $max->x && $current->y <= $max->y) //you will not need this but
       return $current;                                 // still its good to have

   if( ($current->y / $max->y) > ($current->x / $max->x) ) { //y axis needs more trimming
       $r=$current->y / $max->y;
       $current->y = $max->y;
       $current->x = $current->x / $r;
   } else {
       $r=$current->x / $max->x;
       $current->x = $max->x;
       $current->y = $current->y / $r;
   }

   return $current;
}

You just need a few steps:

1. scale = imageWidth / 180;
2. scale = (imageHeight/scale>180) ? imageHeight/180 : scale;

The first one will set the scale factor you need to make the width 180 (based on your comment that it is ALWAYS larger then 180)

The second one will check if the height will be larger then 180 with that scale. If it is, then the scale will be height/180. If its not, you already have the max height.

Then you also need steps to get the actual width and height:

width = imageWidth/scale;
height = imageHeight/scale;

Considering you want to make the imageWidth between 170 and 180 I guess cropping the image is also a possibility. If that is the case you need an additional check

if (width<170) {
  width = 170;
  height = imageHeigh / (imageWidth/170);
  //resize image to width and height
  //crop image to height = 180
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM