在没有库的情况下使用php调整图像大小

时间:2013-10-19 16:06:31

标签: php image resize

我有一段这段代码。

它将图像收费到我的网络服务器并将名称保存到我的sql中。

所有工作除了调整大小时间。我在http://php.net/manual/en/function.imagecopyresampled.php

上找到了这个功能

非常感谢任何帮助。

感谢。

<?php
if(isset($_FILES["AddPhoto"])) {

    if ($_FILES["AddPhoto"]["error"] > 0) {
        $newImgMessError = $MYCARDEDIT0058;
    }
    else {
        $fileName = $_FILES['AddPhoto']['name'];
        $tmpName  = $_FILES['AddPhoto']['tmp_name'];
        $fileSize = $_FILES['AddPhoto']['size']/1024;
        $fileType = $_FILES['AddPhoto']['type'];
        $fileExtension = end(explode(".", $fileName));

        if(($fileType == "image/gif" || $fileType == "image/jpeg" || $fileType == "image/pjpeg" || $fileType == "image/png" || $fileType == "image/x-png") && $fileSize < 1000000) {

            $newFileName = md5(date('u').rand(0,99)).".".$fileExtension;
            $imagePath = "assets/picts/".$newFileName;




// THIS PART DO NOT WORK            
// Set a maximum height and width
$width = 200;
$height = 200;

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($imagePath);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($imagePath);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
$imagePath = imagejpeg($image_p, null, 100);            








            $result = @move_uploaded_file($tmpName, $imagePath);

            $request = mysql_query("SELECT ".$TypeField."Images FROM $TypeFiche WHERE $TypeId='$cardId'");
            $var2 = mysql_fetch_array($request);

            mysql_query("UPDATE ".$TypeFiche." SET `".$TypeField."Images`='".$var2[$TypeField.'Images'].$newFileName.",' WHERE $TypeId='$cardId'");

            if (!$result) {
                $newImgMessError = $INSCRIPTION0074." <b>".$fileName."</b>. ".$INSCRIPTION0075."<br />";
            }
            if ($result) {
                $newImgMessError = $INSCRIPTION0076." <b>".$fileName."</b> ".$INSCRIPTION0077."<br />";
            }
        }
    }
}

?>

1 个答案:

答案 0 :(得分:0)

1。您必须先将文件移动到新目录,然后才能调整其大小。把你的调整大小放在这一行之下:

$result = @move_uploaded_file($tmpName, $imagePath);

否则调整大小代码会尝试访问尚不存在的文件。

2。您必须将新图像写为文件输出,因此请替换该行

 $imagePath = imagejpeg($image_p, null, 100);    

用这个

imagejpeg($image_p, $imagePath, 100); 

http://php.net/manual/en/function.imagejpeg.php