PHP GD创建了一个PNG文件,当我尝试在同一文件上使用imagefronpng()时失败


PHP GD creates a PNG file and fails when I try to use imagefronpng() on that same file

我正在使用PHP GD库来处理一些图像以创建一个模因生成器。我以前从未使用过任何语言的图像处理。

首先,我拍摄上传的 trhough POST 图像,并根据我设置的最大宽度和高度参数使用 GD 调整其大小。调整大小的图像将保存到服务器,并在下一页中向用户显示,并使用用于设置标题的表单。此表单包含所有标题信息:标题文本、字体大小和每个标题的 x-y 位置。

回到服务器中,使用标题表单中的数据,我从上一步中调整大小的文件创建 GD 资源并添加标题。

它就像一个带有 .gif 和 .jpg/.jpeg 文件的魅力,但是当我使用 PNG 文件时,它会失败。当我调整上传文件的大小时,它会正确保存,但在第二步中,当我尝试使用调整大小的文件创建 GD 资源时,它会引发此错误:消息:imagecreatefrompng() [function.imagecreatefrompng]:"./images/tmp/Phineas_talks_to_Perry1.png"不是有效的 PNG 文件

我猜这与第一次创建文件的过程(调整大小)有关。不是文件不存在,我每次都会仔细检查。我把它下载回我的电脑,用毕加撒打开它,它很好。

我正在 CodeIgniter 之上工作,在 Apache 服务器(Go Daddy 共享主机)上工作。

这是我使用的两个函数的代码,它们包装在一个类中:(注释是西班牙语的,请随意忽略它们)

class Imageprocessing
{
    public function __construct()
    {
        $this->ci =& get_instance();
        $this->ci->load->helper('file');
    }

public function resize( $path, $overwrite = false, $destination = null, $name = null )
{
    $output = 0;        
    //Si están seteados los parámetros de ancho y altura máximos
    if( isset( $this->max_W ) && isset( $this->max_H ) )
    {
        //Si la ubicación que recibimos es un archivo válido
        if( is_file( $path ) )
        {
            //Si el archivo es de tipo imagen
            if( $this->is_image( $path ) )
            {                    
                $pathinfo = pathinfo( $path );
                $ext = $pathinfo['extension'];
                $file = $pathinfo['filename'];            
                $dir = $pathinfo['dirname'] . '/';
                //Creando el recurso de imagen GD, usando la función apropiada según el mime type
                if( $ext == 'jpeg' || $ext == 'jpg' )
                {
                    $src = imagecreatefromjpeg( $path );
                }
                elseif( $ext == 'png' )
                {
                    $src = imagecreatefrompng( $path );
                }
                elseif( $ext == 'gif' )
                {
                    $src = imagecreatefromgif( $path );
                }
                //determinando el ancho y alto actual de la imagen
                $W = imageSX( $src );
                $H = imageSY( $src );
                //Si alguno de los dos parámetros excede el máximo permitido, calculamos las nuevas dimensiones de la imagen
                if( $W > $this->max_W || $H > $this->max_H )
                {        
                    //Si la foto es más alta que ancha
                    if( $W < $H )
                    {
                        /*Redimensionamos la altura al máximo permitido
                        /*Calculamos la proporción en que varió la altura y disminuimos el ancho en esa misma proporción
                        */
                        $new_H = $this->max_H;                            
                        $new_W = $W * ( $this->max_H / $H );
                    }
                    elseif( $W > $H )
                    {
                        /*Redimensionamos el ancho al máximo permitido
                        /*Calculamos la proporción en que varió el ancho y disminuimos la altura en esa misma proporción
                        */
                        $new_W = $this->max_W;                            
                        $new_H = $H * ( $this->max_W / $W );
                    }
                    else
                    {
                        $new_W = $this->max_W;
                        $new_H = $this->max_W;
                    }
                    //determinando la carpeta de destino y el nombre del nuevo archivo
                    if( $overwrite )
                    {
                        $destination = $path;
                    }
                    else
                    {
                        if( ! isset( $destination ) || empty( $destination ) )
                        {
                            $destination = $dir;
                        }
                        //si $destination no es un directorio válido
                        elseif( ! is_dir( $destination ) )
                        {
                            $destination = $dir;                        
                        }
                        if( ! isset( $name ) || empty( $name ) )
                        {
                            $destination .= "{$file}_" . (int) $new_W . 'x' . (int) $new_H . ".{$ext}";
                        }
                        else
                        {
                            //filtrar para que sea un nombre de archivo válido
                            $destination .= filter_var( str_replace( ' ', '_', $name ), FILTER_SANITIZE_URL ) . ".{$ext}";
                        }
                    }                    
                    //creamos la nueva imagen, redimensionada                        
                    $dst = imagecreatetruecolor( $new_W, $new_H );
                    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_W, $new_H, $W, $H );
                    //según el mime
                    if( $ext == 'jpg' || $ext = 'jpeg' )
                    {
                        $success = imagejpeg( $dst, $destination, 100 );
                    }
                    elseif( $ext == 'png' )
                    {
                        $success = imagepng( $dst, $destination );
                    }
                    elseif( $ext == 'gif' )
                    {
                        $success = imagegif( $dst, $destination );
                    }
                    if( $success )
                    {
                        $output = array( 'src' => $destination, 'width' => $new_W, 'height' => $new_H );
                    }
                    unset( $src, $dst );
                }
                else
                {
                    $output = -1;
                }                    
            }
            else
            {
                $error = 'Debes usar un archivo de imagen';
            }                
        }
        else
        {
            $error = 'Debes especificar una ubicación de archivo válida';
        }
    }
    else
    {
        $error = 'Para usar la función ' . __METHOD__ . ' de la clase ' . __CLASS__ . ' se deben especificar los parámetros de ancho máximo permitido ( max_W ) y altura máxima permitida ( max_H )';
    }
    if( isset( $error ) && ! empty( $error ) )
    {
        trigger_error( $error, E_USER_WARNING );
    }
    return $output;
}    
public function caption( $path, $captions, $overwrite = false, $destination = null, $name = null )
{
    $output = false;
    if( is_file( $path ) )
    {
        if( $this->is_image( $path ) )
        {
            if( is_array( $captions ) )
            {                
                $pathinfo = pathinfo( $path );
                $ext = $pathinfo['extension'];                    
                $file = $pathinfo['filename'];                    
                $dir = $pathinfo['dirname'] . '/';
                //Creando el recurso de imagen GD, usando la función apropiada según el mime type
                if( $ext == 'jpeg' || $ext == 'jpg' )
                {
                    $src = imagecreatefromjpeg( $path );
                }
                elseif( $ext == 'png' )
                {
                    $src = imagecreatefrompng( $path );
                }
                elseif( $ext == 'gif' )
                {
                    $src = imagecreatefromgif( $path );                
                }
                $color = imagecolorallocate( $src, 255, 255, 255 );
                foreach( $captions as $caption )
                {
                    imagefttext( $src, $caption['font-size'], 0, $caption['x'], $caption['y'] + $caption['font-size'], $color, './fonts/impact.ttf', $caption['text'] );
                }
                if( $overwrite )
                {
                    $destination = $path;                    
                }
                else
                {
                    if( ! isset( $destination ) || empty( $destination )  )
                    {
                        $destination = $dir;
                    }
                    elseif( ! is_dir( $destination ) )
                    {
                        $destination = $dir;
                    }
                    if( ! isset( $name ) || empty( $name )  )
                    {
                        $destination .= "{$file}_caption.{$ext}";
                    }
                    else
                    {
                        //filtrar para que sea un nombre de archivo válido
                        $destination .= filter_var( str_replace( ' ', '_', $name ), FILTER_SANITIZE_URL ) . ".{$ext}";
                    }
                }
                //según el mime
                if( $ext == 'jpg' || $ext = 'jpeg' )
                {
                    $success = imagejpeg( $src, $destination, 100 );
                }
                elseif( $ext == 'png' )
                {
                    $success = imagepng( $src, $destination );
                }
                elseif( $ext == 'gif' )
                {
                    $success = imagegif( $src, $destination );
                }
                if( $success )
                {
                    $output = array( 'src' => $destination, 'width' => (int) imageSX( $src ), 'height' => (int) imageSY( $src ) );
                }
                unset( $src );
            }
            else
            {
                $error = 'Los captions deben ingresarse como un array';
            }
        }
        else
        {
            $error = 'Se debe usar un archivo de imagen';
        }
    }
    else
    {
        $error = 'Se debe usar un archivo válido';
    }
    if( isset( $error ) && ! empty( $error ) )
    {
        trigger_error( $error, E_USER_WARNING );
    }
    return $output;        
}    
}
你对此有什么

想法吗?

编辑:您可以尝试我到目前为止在此地址中所做的操作,再次忽略西班牙语,只需上传文件并尝试即可。谢谢!

为了使脚本调整图片大小,它必须大于 640x480

http://unmillondemascotas.org/meme/

问题肯定出在映像创建过程中。我手动将图像上传到服务器并对字幕过程进行了硬编码,它成功了,它创建了一个新的 PNG 文件。然后我尝试再次为同一个文件添加标题,但它失败了。所以,我在编写新的PNG文件时一定做错了什么,但我不知道它是什么。

我对来自 PhpThumb (GD) 保存的图像有同样的问题,因为"输入"图像可以采用任何格式。我修复了它只是确保保存的图像确实是 PNG 文件:

$image->save($path, "PNG");

问候。