使用PHP和GD2调整图像大小。I';我得到了图像和黑色背景

使用PHP和GD2调整图像大小。I';我得到了图像和黑色背景,php,gd,gd2,Php,Gd,Gd2,我正在创建一个动态类来生成各种图像 ImagesUtils.php <?php class ImagesUtils { private $nombre_imagen = null; private $imagen = null; private $extension = null; private $directorio = null; private $width = null; private $height = null; p

我正在创建一个动态类来生成各种图像

ImagesUtils.php

<?php
class ImagesUtils
{
    private $nombre_imagen = null;
    private $imagen = null;
    private $extension = null;
    private $directorio = null;

    private $width = null;
    private $height = null;
    private $tipo = null;

    private $final_width = null;
    private $final_height = null;
    private $nuevo_nombre = null;
    private $nuevo_directorio = null;

    public function __construct($imagen, $directorio = '')
    {
        $this->directorio = realpath("..".DS."data".DS."storage".DS."files".DS.$directorio);

        $this->imagen = $this->directorio.DS.$imagen;
        $this->nombre_imagen = $imagen;

        $this->extension = substr($imagen, strrpos($imagen, '.') + 1, strlen($imagen));

        $propiedades = getimagesize($this->imagen);

        $this->width = $propiedades["0"];
        $this->height = $propiedades["1"];
        $this->tipo = $propiedades["2"];
    }

    public function Resize($width = null, $height = null, $proporcion = true)
    {
        $this->final_width = $width;
        $this->final_height = $height;

        if(true == $proporcion)
            self::proporcion($width, $height);

        $imagen = imagecreatefromjpeg($this->imagen);

        $nueva_imagen = imagecreatetruecolor($this->final_width, $this->final_height);

        imagecopyresampled($nueva_imagen, $imagen, 0, 0, 0, 0, $this->final_width, $this->final_height, $this->width, $this->height);

        return imagejpeg($image, $this->nueva_imagen);
    }
}
?>
这个代码很好用。。。但如果我用这个:

$procesar_imagen->Resize(300, 300);
生成的最终图像如下所示:

输入图像为:


我不知道怎么解决它。。。函数的作用是:从照片的纵横比中返回新的高度和宽度。。。我检查了,值是正确的,返回的宽度是300(最终图像宽度是300…但算上黑色区域)。

我知道您正在尝试编写自己的代码,但您可能想看看这个:

$procesar_imagen->Resize(300, 300);