使用 php 调整图像大小,而无需库


Resize an image with php without a library

我有一段代码。

它将图像向我的 Web 服务器收费,并将名称保存到我的 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. 必须先将文件移动到新目录,然后才能调整其大小。将调整大小放在此行下方:

$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