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

标签 php image-processing png gd

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

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

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

它对 .gif 和 .jpg/.jpeg 文件很有用,但当我使用 PNG 文件时它就失败了。当我调整上传文件的大小时它被正确保存,但在第二步,当我尝试使用调整大小的文件创建 GD 资源时它抛出此错误:消息:imagecreatefrompng()[function.imagecreatefrompng]:'./images/tmp/Phineas_talks_to_Perry1.png' 不是有效的 PNG 文件

我猜这与第一次创建文件(调整大小)的过程有关。不是文件不存在,我每次都会仔细检查。然后我将它下载回我的电脑,用 Picassa 打开它,一切正常。

我在 Apache 服务器(Go Daddy 共享主机)上基于 CodeIgniter 工作。

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

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");

问候。

关于PHP GD 创建一个 PNG 文件,当我尝试在同一文件上使用 imagefronpng() 时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10955422/

相关文章:

php - 使用 GROUP BY - MYSQL 将时间作为类别列表

php - 如果不存在则插入mysql,如果存在则不更新

python - 如何将最相似的 Unicode 字符返回到图像的一部分?

python - Numpy 图像切片返回黑色补丁/错误值

php - Zend 中缓慢的 Postgres 查询

php - 全选复选框

swift avfoundation AVCapturePhotoCaptureDelegate 捕获方法

c# - 使用 wpf 存储在外部 dll 中的引用图像

ios - 如何在 Swift 中压缩 PNG 文件?

php - 如何检测调色板 PNG 文件?