Add watermark to image (Base64) and convert it

佐手、 提交于 2019-12-12 04:59:35

问题


I have this PHP script (below): I getting base64 string using POST, than use imagecreatefromstring function and then trying to add watermark and save it. But the file is empty on the server after upload. What i'm doing wrong?

    <?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";
    }


?>

Can anyone help me to solve this issue?


回答1:


add this code before in order to check if your image was created

$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.';
}

//



来源:https://stackoverflow.com/questions/35585358/add-watermark-to-image-base64-and-convert-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!