繁体   English   中英

图像调整大小和裁剪

[英]Image Resize & Crop

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

此代码使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM