如何使用PHP调整图像文件的大小

时间:2014-07-20 06:33:07

标签: php html database image pdo

我想做的是将每张图片调整为300x300。我的问题是在我当前的代码中移动到上传文件夹的一些图像文件很大。我希望上传文件夹中的所有图像文件大小为300x300。

当前的PHP代码:

<?php
include_once('../dbc/database.php');

$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$emailCodeResult = isset($_POST['emailCodeResult']) ? $_POST['emailCodeResult'] : "";

$imageLink = isset($_POST['imageLink']) ? $_POST['imageLink'] : "";
const path = "Oppa/upload/";
$s= explode(path,$imageLink);
unlink("../upload/".$s[1]);

$email = isset($_POST['email']) ? $_POST['email'] : "";

$type = $_FILES["imageInput"]["type"];
$ext = end(explode('/', $type));
$filename = uniqid() . '_' .$emailCodeResult . '.' . $ext; 
move_uploaded_file($_FILES["imageInput"]["tmp_name"], "../upload/" . $filename);
$location = "Oppa/upload/" . $filename;

if(!empty($_POST['email'])) {

        $q = "UPDATE tbl_user SET user_image = '$location' WHERE user_email= :email ";
        $query = $db->prepare($q);
        $query->bindParam(':email', $email);
        $results = $query->execute();
        echo "1";

}
?>

1 个答案:

答案 0 :(得分:0)

以下是调整图片大小的代码。愿这可以帮到你

             $path = getcwd();
             $oldpic = $path.'/images/test.jpg'; //your image path
             $array = explode("/",$oldpic);
             $count = count($array);
             $name = $array[$count-1];

             $src = $oldpic;
             $dest = $path."/images/thumbnail/".$name; // resized image

             //Genrating the image from there extension
             $size = getimagesize($src);
             switch($size["mime"]){

                        case "image/jpeg":
                          $source_image = imagecreatefromjpeg($src); //jpeg file
                        break;

                        case "image/gif":
                          $source_image = imagecreatefromgif($src); //gif file
                        break;

                        case "image/png":
                          $source_image = imagecreatefrompng($src); //png file
                        break;

                        default:
                          $source_image=false;
                        break;
             }
             $width = imagesx($source_image);
             $height = imagesy($source_image);
             $newwidth=300;
             $newheight= 300;
             $virtual_image = imagecreatetruecolor($newwidth, $newheight);
             imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
             imagejpeg($virtual_image,$dest,100);