Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arbitrary image resizing in PHP

Tags:

php

What would be the best way to resize images, which could be of any dimension, to a fixed size, or at least to fit within a fixed size?

The images come from random urls that are not in my control, and I must ensure the images do not go out of an area roughly 250px x 300px, or 20% by 50% of a layer.

I would think that I would first determine the size, and if it fell outside the range, resize by a factor, but I am unsure how to work out the logic to resize if the image size could be anything.

edit:I do not have local access to the image, and the image url is in a variable with is output with img src=..., I need a way to specify the values of width and height tags.

like image 623
Joshxtothe4 Avatar asked Mar 09 '26 05:03

Joshxtothe4


1 Answers

It's easy to do with ImageMagick. Either you use convert command line tool via exec or you use http://www.francodacosta.com/phmagick/resizing-images .
If you use 'convert' you can even tell ImageMagick to just resize larger images and to not convert smaller ones: http://www.imagemagick.org/Usage/resize/

If you don't have local access, you won't be able to use ImageMagick:

<?php
$maxWidth  = 250;
$maxHeight = 500;

$size = getimagesize($url);
if ($size) {
    $imageWidth  = $size[0];
    $imageHeight = $size[1];
    $wRatio = $imageWidth / $maxWidth;
    $hRatio = $imageHeight / $maxHeight;
    $maxRatio = max($wRatio, $hRatio);
    if ($maxRatio > 1) {
        $outputWidth = $imageWidth / $maxRatio;
        $outputHeight = $imageHeight / $maxRatio;
    } else {
        $outputWidth = $imageWidth;
        $outputHeight = $imageHeight;
    }
}
?>
like image 88
Sven Lilienthal Avatar answered Mar 10 '26 19:03

Sven Lilienthal