繁体   English   中英

使用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/zh/function.imagejpeg.php

暂无
暂无

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

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