繁体   English   中英

使用GD调整图像大小的PHP

[英]image resizing php using GD

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM