图像使用GD调整大小

时间:2016-06-22 04:06:25

标签: php html image gd

我已经读过gd库,我可以调整图像大小,但我找不到正确的方法。我试图找到的是一个调整大小的函数 - 上传图像(上传/调整大小)并返回调整大小后的图像的路径,以便将其保存在数据库中供以后使用。我尝试使用我发现的一些功能,但我做错了什么。我已经在我的Windows 7和我的phpinfo()中安装了wamp64,似乎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);...
    }
}
?>

1 个答案:

答案 0 :(得分:0)

我在这段代码中看不到任何用于重新生成图像的代码, 以下是调整图像大小的简单方法,请将图像路径存储在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`
?>