【问题标题】:PHP: Generating PNG thumbnail images from PNG source crashes function based on PNG sizePHP:从基于PNG大小的PNG源崩溃函数生成PNG缩略图图像
【发布时间】:2013-02-10 03:37:04
【问题描述】:

我编写了这个小函数来生成较大 jpg/jpeg/png 源的缩略图图像,它在 jpg/jpeg 图像上完美运行,但根据 png 图像的大小,该函数会在不确定点。 300x200 的小图像可以工作,但 2880x1800 之类的图像则不行。

这是我的(带注释的)函数:

function make_thumb($filename, $destination, $desired_width) {
    $extension = pathinfo($filename, PATHINFO_EXTENSION);

    // Read source image
    if ($extension == 'jpg' || $extension == 'jpeg') {
        $source_image = imagecreatefromjpeg($filename); 
    } else if ($extension == 'png') {
        $source_image = imagecreatefrompng($filename); // I think the crash occurs here. 
    } else {
        return 'error';
    }

    $width = imagesx($source_image);
    $height = imagesy($source_image);

    $img_ratio = floor($height / $width);

    // Find the "desired height" of this thumbnail, relative to the desired width
    $desired_height = floor($height * ($desired_width / $width));

    // Create a new "virtual" image
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    // Copy source image at a resized size
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    // Create the physical thumbnail image to its destination 
    if ($extension == 'jpg' || $extension == 'jpeg') {
        $source_image = imagejpeg($virtual_image, $destination); 
    } else if ($extension == 'png') {
        $source_image = imagepng($virtual_image, $destination, 1);
    } else {
        return 'another error';
    }
}

我发现与我提到类似问题的唯一文档是this。这是我的问题吗?有什么解决办法吗?为什么会这样?

【问题讨论】:

    标签: php image png thumbnails


    【解决方案1】:

    您很可能内存不足。 2880 x 1800 的真彩色大约需要 20 兆字节。

    检查您的 php.ini 是否有 memory_limit

    【讨论】:

      【解决方案2】:

      我是个白痴。那或 PHP 在处理大型 PNG 图像方面确实很糟糕。 PHP 文档here for imagepng() 中的这条评论说:

      我的脚本无法完成:致命错误:XX 字节的允许内存大小已用尽(试图分配 XX+n 字节)。

      我发现 PHP 处理未压缩格式的图像:我的输入图像是 8768x4282@32 位 => 每个内存中的副本约 150 MB。

      作为一种解决方案,您可以检查尺寸并拒绝任何太大的东西,或者像我一样使用 ini_set('memory_limit','1024M');在页面开始时(如果您的服务器有足够的板载内存)。

      所以,记得使用ini_set('memory_limit','1024M'); 来增加你的可用内存限制!!!

      【讨论】:

        猜你喜欢
        • 2017-04-22
        • 2012-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-18
        • 1970-01-01
        • 2019-07-27
        • 2018-10-14
        相关资源
        最近更新 更多