PHP将文本添加到图像并保存

问题描述 投票:0回答:1

我试图让PHP文件为上传的图像添加ID并重新保存图像。由于某种原因,下面的代码不起作用,即使它看起来非常类似于我在网上找到的其他示例。我究竟做错了什么?

    $productStyle = isset($_POST['productStyle']) ? encodechars($_POST['productStyle']) : "";
    $productSize = isset($_POST['productSize']) ? encodechars($_POST['productSize']) : "";
    $itemID = isset($_POST['itemID']) ? encodechars($_POST['itemID']) : "";

    if ($productStyle!=""){
        $fileLocation ='/home/abcdefg/public_html/uploads/'.$productStyle;
        $photoLoc = $fileLocation . "/" . $itemID.".png";
        if(!is_dir($fileLocation)) {
            mkdir($fileLocation , 0777); //create directory if it doesn't exist
        }

        //add id to image
        $im = imagecreatefrompng($_FILES["file"]["tmp_name"]);
        $font = 'Verdana.ttf';  //<-- this file is included in directory
        $grey = imagecolorallocate($im, 128, 128, 128);
        imagettftext($im, 10, 0, 11, 20, $grey, $font, $itemID);

        imagepng($im, $photoLoc);  //<-- This does not work
        imagedestroy($im);   

        //move_uploaded_file($_FILES["file"]["tmp_name"], $photoLoc);  //<-- This will move the file to the correct folder but without the text added 

    }
php php-gd
1个回答
1
投票

首先,移动原始文件,然后在加水印后删除。

$productStyle = isset($_POST['productStyle']) ? encodechars($_POST['productStyle']) : "";
$productSize = isset($_POST['productSize']) ? encodechars($_POST['productSize']) : "";
$itemID = isset($_POST['itemID']) ? encodechars($_POST['itemID']) : "";

if ($productStyle!=""){
    $fileLocation ='/home/abcdefg/public_html/uploads/'.$productStyle;
    $photoLoc = $fileLocation . "/" . $_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
    if(!is_dir($fileLocation)) {
        mkdir($fileLocation , 0777); //create directory if it doesn't exist
    }

    //add id to image
    $im = imagecreatefrompng($photoLoc);
    $font = 'Verdana.ttf';  //<-- this file is included in directory
    $grey = imagecolorallocate($im, 128, 128, 128);
    imagettftext($im, 10, 0, 11, 20, $grey, $font, $itemID);

    imagepng($im, $photoLoc);  //<-- This does not work
    imagedestroy($im);   
    unlink($photoLoc);
    //move_uploaded_file($_FILES["file"]["tmp_name"], $photoLoc);  //<-- This will move the file to the correct folder but without the text added 

} 

或者只是改变

$im = imagecreatefrompng($_FILES["file"]["tmp_name"]);

$im = imagecreatefrompng($_FILES["file"]["name"]);
© www.soinside.com 2019 - 2024. All rights reserved.