为图像添加水印(Base64)并进行转换


Add watermark to image (Base64) and convert it

我有这个PHP脚本(如下):我使用 POST 获取 base64 字符串,而不是使用 imagecreatefromstring 函数,然后尝试添加水印并保存它。但是上传后服务器上的文件是空的。我做错了什么?

    <?php
    if($_SERVER['REQUEST_METHOD'] == "POST") {
    define('UPLOAD_DIR', 'img/');
    $base64 = base64_decode(preg_replace('#^data:image/[^;]+;base64,#', '', $_POST['string']));
    $stamp = imagecreatefrompng('img/wm.png');
    $im = imagecreatefromstring($base64);

    $marge_right = 10;
    $marge_bottom = 10;
    $sx = imagesx($stamp);
    $sy = imagesy($stamp);
    imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

    $file = UPLOAD_DIR . uniqid() . '.png';
    imagepng($im, $file, 100);

    echo 'ok';
    } else {
    echo "error";
    }

?>

谁能帮我解决这个问题?

之前添加此代码以检查您的映像是否已创建

$im = imagecreatefromstring($base64);
if ($im !== false) {
    header('Content-Type: image/png');
    $marge_right = 10;
    $marge_bottom = 10;
    $sx = imagesx($stamp);
    $sy = imagesy($stamp);
    imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

    $file = UPLOAD_DIR . uniqid() . '.png';
    imagepng($im, $file, 100);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}

//