在PHP中上载时创建新的水印文件

在PHP中上载时创建新的水印文件,php,file,Php,File,我想在正在上载的图像旁边创建一个新的带水印的文件。 我想出了这个代码,但它没有任何作用。PHP不会返回错误。有人知道我做错了什么 function watermark_image(){ $name = basename($_FILES['file_upload']['name']); // Load the watermark and the photo to apply the watermark to $stamp = imagecreatefrompng('wat

我想在正在上载的图像旁边创建一个新的带水印的文件。 我想出了这个代码,但它没有任何作用。PHP不会返回错误。有人知道我做错了什么

function watermark_image(){
    $name = basename($_FILES['file_upload']['name']);

    // Load the watermark and the photo to apply the watermark to
    $stamp = imagecreatefrompng('watermarkMQ.png');
    $im = imagecreatefromjpeg($name);

    // Set the margins for the stamp and get the height/width of the stamp image
    $marge_right = 0;
    $marge_bottom = 0;
    $sx = imagesx($stamp);
    $sy = imagesy($stamp);

    // Copy the stamp image onto our photo using the margin offsets and the photo 
    // width to calculate positioning of the stamp. 
    imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

    // Save and free memory
    imagejpeg($im, 'wm_' . $name);
    imagedestroy($im);
}

您犯了多个错误:

$name = basename($_FILES['file_upload']['name']);
                                       ^^^^^^^^
该参数是用户计算机上的文件名。上载到服务器的文件实际上位于['tmp_name']

然后您无法检查是否成功-PHP不会返回错误。但GD函数在失败时确实返回布尔值false,这不是您要查找的:

$im = imagecreatefromjpeg($name);
if ($im === false) {
   die("Failed to open $name");
}

永远不要假设处理外部资源的操作成功。始终假设失败,检查失败,并将成功视为惊喜。

感谢您的解释。你教我如何更好地用PHP编写代码。我已经编写PHP代码3周了。我现在确实收到一个错误,但这是“打开失败”错误,它会随机生成一个代码?:我回显$name以查看它得到了什么,现在我看到它随机生成了一个我需要上传文件名的代码