使用 GD 调整图像大小

Posted

技术标签:

【中文标题】使用 GD 调整图像大小【英文标题】:image resizing php using GD 【发布时间】:2016-06-22 04:06:25 【问题描述】:

我已经阅读了 gd 库,我可以调整图像的大小,但我找不到正确的方法。我想要找到的是一个函数,它调整大小 - 上传图像(到 /uploads/resized)并返回调整大小的图像的路径,以便将其保存在数据库中以供以后使用。我尝试使用我发现的一些功能,但我做错了。我在 Windows 7 中安装了 wamp64,在我的 phpinfo() 中似乎启用了 gd。它不必是 gd 我可以使用任何调整图像大小的函数。任何提示都会有所帮助。

GD Support  enabled
GD Version  bundled (2.1.0 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.5.5
GIF Read Support    enabled
GIF Create Support  enabled
JPEG Support    enabled
libJPEG Version 9 compatible
PNG Support enabled
libPNG Version  1.5.18
WBMP Support    enabled
XPM Support enabled
libXpm Version  30411
XBM Support enabled
WebP Support    enabled

这是我用来上传图像并将有关它们的信息存储到数据库的 php 文件:

<?php
// just in case, let's turn on the errors
include_once("config.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') 
    $file = isset($_FILES['fileToUpload']['tmp_name']) ? $_FILES['fileToUpload'] : null;
    // start validation
    try 
        // check if file was NOT provided
        if (!$file ||
            !file_exists($file['tmp_name']) || 
            !is_uploaded_file($file['tmp_name']) || 
            $file['error'] !== UPLOAD_ERR_OK) 
            throw new Exception('No file was given.');
        
        // check if file is NOT an image
        $size = getimagesize($file['tmp_name']);
        if ($size === false) 
            throw new Exception('File is not an image.');
        
        // check if file already exists
        $target_dir = 'uploads/';
        $target_file = $target_dir . basename($file['name']);
        if (file_exists($target_file)) 
            throw new Exception('File already exists.');
        
        // check file size is too large
        if ($file['size'] > 2000000) 
            throw new Exception('File is too large.');
        
        // check file extension is NOT accepted
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, ['jpg', 'png', 'gif'])) 
            throw new Exception('Only JPEG, PNG & GIF files are allowed.');
        
        // if it passes all checks, try uploading file
        //changing the files name 
        $temp = explode(".", $_FILES["fileToUpload"]["name"]); // edw
        $newfilename = round(microtime(true)) . '.' . end($temp); // edw
        $target_file_renamed = $target_dir . $newfilename;   //edw
        if (!move_uploaded_file($file['tmp_name'], $target_file_renamed))  
            throw new Exception('There was an error uploading your file.');
        
        // if we reach this point, then everything worked out!
        //echo 'The file ' . basename($file['name']) . ' has been uploaded.';


        //code to resize and save image to uploads/resized and get the path

        //code to insert into database with pdo
        session_start();
        try
        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

        //Code to get photo_category_id
        $sth = $con->prepare('SELECT photo_category_id FROM photo_categories WHERE photo_category = :parameter');
        $sth->bindParam(':parameter', $_POST['category'], PDO::PARAM_STR);
        $sth->execute();
        $idis = $sth->fetchColumn(); //echo $idis will return the photo_category_id

        //Code to update the photos table
        $likes = 0;
        $sql = "INSERT INTO photos(photo_name, photo_text, photo_path, photo_lat, photo_lng, photo_likes, username, photo_category_id)
        VALUES(:name, :text, :path, :lat, :lng, :likes, :username, :category)";
        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "name", basename($file['name']), PDO::PARAM_STR );
        $stmt->bindValue( "text", $_POST['description'], PDO::PARAM_STR );
        $stmt->bindValue( "path", $target_file_renamed, PDO::PARAM_STR );
        $stmt->bindValue( "lat", $_POST['lat'], PDO::PARAM_INT );
        $stmt->bindValue( "lng", $_POST['lng'], PDO::PARAM_INT );
        $stmt->bindValue( "likes", $likes, PDO::PARAM_INT );
        $stmt->bindValue( "username", $_SESSION["user"]->username, PDO::PARAM_STR );
        $stmt->bindValue( "category", $idis, PDO::PARAM_INT );
        $stmt->execute();



        echo 'The file has been uploaded!';
        //echo 'The file ' . basename($file['name']) . ' has been uber fully uploaded.';
        catch (PDOException $e) 
        echo $e->getMessage();
        
     catch (Exception $e) 
        echo $e->getMessage(); //by doing echo here we get the message in javascript alert(data);...
    

?>

【问题讨论】:

看看这是否有帮助:***.com/questions/28002244/… 它解决了我的问题。非常感谢:) 没问题。如果它有效,请不要羞于支持该答案;) 【参考方案1】:

我在此代码中看不到任何用于调整图像大小的代码, 这是调整图片大小的简单方法,请将图片路径保存在db中以备将来使用。

    <?php

/*
 * PHP GD
 * resize an image using GD library
 */

// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb);
imagedestroy($thumb);`enter code here`
?>

【讨论】:

以上是关于使用 GD 调整图像大小的主要内容,如果未能解决你的问题,请参考以下文章

使用巨大(6000+ 宽)图像调整 GD 图像大小(带 CI)

仅显示图像的某些部分并使用 GD 调整其大小

使用gd在php中调整图像大小后的黑色背景

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

使用 PHP GD 调整图像大小并保存图像。这段代码有啥问题?

Codeigniter GD 库图像调整大小不起作用