Jump to content

Constrained image->size issue


evanmcd
 Share

Recommended Posts

Hi everyone,

I'm trying to get image resizing to work in what I thought was a pretty standard way: the final image needs to maintain it's aspect ratio, not be cropped and be as tall or as wide as it can be up to a certain height and width.

For me the max width and height is 410.  So, I have the following code:

   $photo = $entry->photo;
   $options = array('upscaling'=>true,'cropping'=>false,'quality'=>80);
   if($photo->width > $photo->height) {
    $photo = $photo->size(410,0,$options);
   } else {
    $photo = $photo->size(0,410,$options);
   }
   $entry->photo = $photo;
   $entry->save();

Unfortunately, if I upload an image that's 1023x1852, for example, it doesn't get resized at all.  What could I be doing wrong?

Thanks for any help you all can offer.

Link to comment
Share on other sites

Not very familiar what happens behind the scenes, but have you tried $photo->width(410, $options) and $photo->height(410, $options) instead of size? Size gives you exact size you are asking and might get confused with 0 height / width.

Link to comment
Share on other sites

A resized image can't be sent back to the field to replace the image it was resized from. That's because it has a filename reflecting it's resize properties, and so it's considered a variation rather than a source image. Most likely your resized image was created and on the file system, but PW saw the source image and stuck with it. 

There isn't really any reason to replace a source image with a size variation here, because your size variation will be cached. It won't literally create it every time. But your code as it exists now will execute a page save every time. So you would be much better off just doing this in your template code:

$photo = $entry->photo;
$options = array('upscaling'=>true,'cropping'=>false,'quality'=>80);
if($photo->width > $photo->height) {
  $photo = $photo->size(410,0,$options);
} else {
  $photo = $photo->size(0,410,$options);
}

// the above only created a new image the first time it was run
// so it's perfectly efficient to leave it there. 
// $photo is ready to use

echo "<img src='$photo->url' alt='$photo->description' />";

Also, if you want to set max dimensions for an uploaded image, then you can set this from the image field's settings. 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...