首页 > 解决方案 > 我如何在 PHP 中使用 imagescale 调整图像大小

问题描述

我尝试使用以下方法调整图像大小:

代码

$thumbimg = $img->resizeImage($thumb, 200, 200);

public function resizeImage($imagePath,$new_width,$new_height) {

            $fileName = pathinfo($imagePath,PATHINFO_FILENAME);
            $ext = pathinfo($imagePath,PATHINFO_EXTENSION);
            $fullPath = pathinfo($imagePath,PATHINFO_DIRNAME)."/".$fileName.'.'.$ext;
            if (file_exists($fullPath)) {
                return $fullPath;
            }
            $image = $this->openImage($imagePath);
            if ($image == false) {
                return null;
            }
            $width = imagesx($image);
            $height = imagesy($image);
            $imageResized = imagecreatetruecolor($width, $height);

            if ($imageResized == false) {
                return null;
            }
            $image = imagecreatetruecolor($width , $height);

            $imageResized = imagescale($image,$new_width,$new_height);
            touch($fullPath);
            $write = imagepng($imageResized,$fullPath);
            if (!$write) {
                imagedestroy($imageResized);    
                return null;
            }
            imagedestroy($imageResized);
            return $fullPath;
        }

实际它以原始宽度和高度保存我的图像。但为什么?怎么了?

标签: phpimage

解决方案


如果$imagePath引用现有图像,$fullPath则将引用同一文件。因此,要么文件存在,在这种情况下返回,要么文件不存在,在这种情况下,您无法打开图像并null返回。无论哪种方式,都不使用图像调整大小代码。


推荐阅读