问题
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