Finglish
Finglish

Reputation: 9976

php imagemagick - how to square an image in the middle of a white square without cropping

I have a series of images on white backgrounds.

My problem is they are in a variety of shapes and sizes and I want them to all be equal in size and all centred in a square ratio without cropping and losing any of the actual image.

Below is my best attempt to date (using imagemagik), but the is not scaling it is just cropping square at 80x80 and losing most of the content

    $im = new Imagick("myimg.jpg");

    $im->trimImage(20000);

    $im_props = $im->getImageGeometry();

    $width = $im_props['width'];
    $height = $im_props['height'];
    $diff = abs($width-$height);

    $color=new ImagickPixel();
    $color->setColor("white");

    if($width > $height){
        $im->thumbnailImage(80, 0);
        $im->borderImage($color, ($diff/2), 0);
    }else{
        $im->thumbnailImage(0, 80);
        $im->borderImage($color, 0, ($diff/2));
    }

    $im->cropImage (80,80,0,0);

    $im->writeImage("altimg.jpg");

Any help gratefully recieved

Upvotes: 3

Views: 2551

Answers (1)

Finglish
Finglish

Reputation: 9976

Thanks @Mark Setchel for pointing me in the right direction. I managed to achieve what I wanted, (an un-cropped image centred in a white square and trimmed to the longest side).

I have voted up your comments but thought I would post my final code for completeness.

    $im = new Imagick("myimg.jpg");

    $im->trimImage(20000);

    $im->resizeImage(80, 80,Imagick::FILTER_LANCZOS,1, TRUE);
    $im->setImageBackgroundColor("white");

    $w = $im->getImageWidth();
    $h = $im->getImageHeight();

    $off_top=0;
    $off_left=0;

    if($w > $h){
        $off_top = ((80-$h)/2) * -1;
    }else{
        $off_left = ((80-$w)/2) * -1;
    }

    $im->extentImage(80,80, $off_left, $off_top);

    $im->writeImage("altimg.jpg");

Upvotes: 8

Related Questions