PHP 从上传的文件创建缩略图并移动到服务器


PHP create thumbnail from uploaded file and moving to server

我在从上传的图像文件创建缩略图,然后将其上传到服务器时遇到了问题。

截至目前,我有一个函数来创建缩略图,将其保存为临时并将其返回给调用者。

然后我尝试做的是上传带有move_uploaded_file(临时拇指,路径)创建的拇指图像;

下面是 createThumb 函数和调用方:

function createThumb( $image, $thumbWidth )
{
  // load image and get image size
  $img = imagecreatefromjpeg( "{$image}" );
  $width = imagesx( $img );
  $height = imagesy( $img );
  // calculate thumbnail size
  $new_width = $thumbWidth;
  $new_height = floor( $height * ( $thumbWidth / $width ) );
  // create a new temporary image
  $tmp_img = imagecreatetruecolor( $new_width, $new_height );
  // copy and resize old image into new image 
  imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  return $tmp_img;
}
return $tmp_img; // Here I return the new image. Is this the proper way to get a binary image back??

这是调用方:

$thumb = createThumb($_FILES['propform-previmg']['tmp_name'], $max_previmg_width); 
        $filenamepath = $src_dir . '/thumb/' . $_FILES['propform-previmg']['name'];
        if ( !move_uploaded_file($thumb, $filenamepath ))
            echo "Error moving file {$filenamepath}";

我尝试直接上传上传的文件,而无需先尝试制作缩略图,并且效果很好。所以我想我从 createThumb 函数返回的变量有一些错误,但我无法弄清楚到底是什么。

另外,我需要从调用方代码上传,而不是在带有imagejpeg(file,path)的createThumb函数中。

谢谢!

手册的第一行:

此函数检查以确保文件名指定的文件是有效的上传文件(这意味着它是通过 PHP 的 HTTP POST 上传机制上传的)。如果文件有效,它将被移动到目的地给出的文件名。

您的缩略图尚未上传,它甚至还不是文件,而只是一个图像资源。要写入映像,请调用类似 imagejpeg($resource, $filename) 的内容将其写入 $filename 中指定的路径。