php如何在不修剪的情况下将图像放在白色正方形中间


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

我有一系列白色背景的图像。

我的问题是它们有各种形状和大小,我希望它们的大小都相等,都以正方形的比例居中,而不会裁剪和丢失任何实际图像。

以下是我迄今为止最好的尝试(使用imagemagik),但没有缩放,只是在80x80处裁剪正方形,并丢失了大部分内容

    $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");

感谢

提供的任何帮助

感谢@Mark Setchel为我指明了正确的方向。我设法达到了我想要的效果(一张以白色正方形为中心并修剪到最长边的未裁剪图像)。

我已经投票通过了你的评论,但为了完整性,我想我会发布我的最终代码。

    $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");