php - 如何使用 GD 调整上传图像的大小并将其转换为 PNG?

标签 php database image png gd

我想允许用户上传各种格式的头像类型图像(至少GIF、JPEG 和PNG),但将它们全部保存为PNG 数据库BLOB。如果图像过大,按像素计算,我想在插入数据库之前调整它们的大小。

使用 GD 进行大小调整和 PNG 转换的最佳方法是什么?

编辑:遗憾的是,只有 GD在我需要使用的服务器上可用,没有 ImageMagick .

最佳答案

<?php                                              
/*
Resizes an image and converts it to PNG returning the PNG data as a string
*/
function imageToPng($srcFile, $maxSize = 100) {  
    list($width_orig, $height_orig, $type) = getimagesize($srcFile);        

    // Get the aspect ratio
    $ratio_orig = $width_orig / $height_orig;

    $width  = $maxSize; 
    $height = $maxSize;

    // resize to height (orig is portrait) 
    if ($ratio_orig < 1) {
        $width = $height * $ratio_orig;
    } 
    // resize to width (orig is landscape)
    else {
        $height = $width / $ratio_orig;
    }

    // Temporarily increase the memory limit to allow for larger images
    ini_set('memory_limit', '32M'); 

    switch ($type) 
    {
        case IMAGETYPE_GIF: 
            $image = imagecreatefromgif($srcFile); 
            break;   
        case IMAGETYPE_JPEG:  
            $image = imagecreatefromjpeg($srcFile); 
            break;   
        case IMAGETYPE_PNG:  
            $image = imagecreatefrompng($srcFile);
            break; 
        default:
            throw new Exception('Unrecognized image type ' . $type);
    }

    // create a new blank image
    $newImage = imagecreatetruecolor($width, $height);

    // Copy the old image to the new image
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    // Output to a temp file
    $destFile = tempnam();
    imagepng($newImage, $destFile);  

    // Free memory                           
    imagedestroy($newImage);

    if ( is_file($destFile) ) {
        $f = fopen($destFile, 'rb');   
        $data = fread($f);       
        fclose($f);

        // Remove the tempfile
        unlink($destFile);    
        return $data;
    }

    throw new Exception('Image conversion failed.');
}

关于php - 如何使用 GD 调整上传图像的大小并将其转换为 PNG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259/

相关文章:

php - 使用 mysql php pdo 从数据库返回一个值

javascript - 如何使网页认为其图像已加载完毕?

c - 使用 GTK[REPEAT] 显示来自 URL 的图像

java - 如何在启动时不显示数据库中的数据?

python - 将库尔德文本(从右到左)添加到图像会返回分隔的字符串

php - 如何获取<yt:accesscontrol>的xml属性?

php - Drupal 和 paypal 快速结帐的集成

php - 仅允许 HTML 净化器中类属性中的特定类

java - JSP 和 Python 可以一起用于同一个数据库吗?

asp.net-mvc - mvc dot.net 模型的多语言数据库模式