图像调整大小&作物

时间:2012-01-25 14:00:57

标签: php codeigniter resize crop

我想调整图像的大小,使调整大小始终填充所需的区域。我希望脚本可以拍摄任意大小的图像,将最短边调整为90px,然后从顶部和底部裁剪(如果是横向,则裁剪左右边),以获得90px×90px的正方形

1 个答案:

答案 0 :(得分:2)

此代码使用GD功能。

源图像可以是JPEG,PNG,GIF或BMP格式。如果您事先知道格式,则可以删除switch语句。结果保存为JPEG。

                    $srcPath = "your source image path goes here";
                    $dstPath = "your destination image path goes here";
                    $size = "90x90";

                    list($w, $h, $type) = getimagesize($srcPath);

                    switch ($type) {
                            case IMAGETYPE_JPEG:
                                    $src = imagecreatefromjpeg($srcPath);
                                    break;
                            case IMAGETYPE_PNG:
                                    $src = imagecreatefrompng($srcPath);
                                    break;
                            case IMAGETYPE_GIF:
                                    $src = imagecreatefromgif($srcPath);
                                    break;
                            case IMAGETYPE_BMP:
                                    $src = imagecreatefrombmp($srcPath);
                                    break;
                    }

                    list($dst_w, $dst_h) = explode('x', $size);
                    $dst = imagecreatetruecolor($dst_w, $dst_h);

                    $dst_x = $dst_y = 0;
                    $src_x = $src_y = 0;

                    if ($dst_w/$dst_h < $w/$h) {
                            $src_w = $h*($dst_w/$dst_h);
                            $src_h = $h;
                            $src_x = ($w-$src_w)/2;
                            $src_y = 0;
                    } else {
                            $src_w = $w;
                            $src_h = $w*($dst_h/$dst_w);
                            $src_x = 0;
                            $src_y = ($h-$src_h)/2;
                    }

                    imagecopyresampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

                    imagejpeg($dst, $dstPath);
                    imagedestroy($src);
                    imagedestroy($dst);