如何在上传时调整固定宽度和高度的图像

时间:2015-03-06 13:44:29

标签: php image-processing gd

当我上传想要以固定宽度和高度压缩的图像时,我已经尝试了很多。我在下面附上了我的编码:

$extension = getExtension($filename);
                    $extension = strtolower($extension);


                    if($extension=="jpg" || $extension=="jpeg" )
                    {
                    $src = imagecreatefromjpeg($tmpFilePath);
                    }

                    else 
                    {
                    $src = imagecreatefromgif($tmpFilePath);
                    }
                    list($width,$height)=getimagesize($tmpFilePath);


                    $newwidth=1000;
                    $newheight=($height/$width)*$newwidth;
                    $tmp=imagecreatetruecolor($newwidth,$newheight);


                    $newwidth1=540;
                    $newheight1=236;
                    $tmp1=imagecreatetruecolor($newwidth1,$newheight1);

                    $newwidth2=253;
                    $newheight2=($height/$width)*$newwidth2;
                    $tmp2=imagecreatetruecolor($newwidth2,$newheight2);

                    $newwidth3=840;
                    $newheight3=365;
                    $tmp3=imagecreatetruecolor($newwidth3,$newheight3);

                    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

                    imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

                    imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$newheight2,$width,$height);

                    imagecopyresampled($tmp3,$src,0,0,0,0,$newwidth3,$newheight3,$width,$height);


                    $filename = "gallery/".$_FILES['egallery_img'.$i]['name'];

                    $filename1 = "gallery/ms". $_FILES['egallery_img'.$i]['name'];

                    $filename2 = "gallery/vs". $_FILES['egallery_img'.$i]['name'];

                    $filename3 = "gallery/medium". $_FILES['egallery_img'.$i]['name'];



                    imagejpeg($tmp,$filename,100);

                    imagejpeg($tmp1,$filename1,100);

                    imagejpeg($tmp2,$filename2,100);

                    imagejpeg($tmp3,$filename3,100);

                    imagedestroy($src);
                    imagedestroy($tmp);
                    imagedestroy($tmp1);
                    imagedestroy($tmp2);

                    imagedestroy($tmp3);

                   $epaname = $filename;
                   unlink($deletImg);
                   unlink($msdeletImg);
                   unlink($vsdeletImg);
                   unlink($mdeletImg);

我得到的是我的编码中给出的宽度,但我得不到正确的高度。

我该如何解决这个问题?还是有人可以建议我解决这个问题的其他方法。如果我修正了宽度和高度,则表示我的图像受到了损坏。再次感谢你。

1 个答案:

答案 0 :(得分:0)

我推荐SimpleImage类,使用起来非常简单。

使用示例:

$img = new SimpleImage('source/path/of/your/image.jpg');

// Resize the image to 320x200
$img->resize(320, 200);

$img->save('destination/path/for/new-image.jpg');

您可以从https://github.com/claviska/SimpleImage

获取