简体   繁体   中英

Adding watermark with PHP

This is my PHP water-marking function:

function img_watermark($image) {
    $stamp = imagecreatefrompng('images/wm.png');
    $im = imagecreatefromjpeg($image); 
    $marge_right = 10;
    $marge_bottom = 10;
    $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));

    // Output and free memory
    header('Content-type: image/png');
    imagepng($im);
    imagedestroy($im);
}

And this is my HTML code:

<img src="<?php img_watermark('images/ornek.jpeg');?>" />

But it just gives me something like this:

.......<, u /,R M 7 a4 3eY&k Tƃ#Ki ' S ^ A 2_^ L* \\ LMSOݺ7 "@ \\k*) 4I 5 < C LP /W 2w qopwnnnw3e ҂g QB\\ _ȋc # F$ `4;; [T b - XגsΩ( J "G ; O=it * ˗> Nw o #¨ 8 J wz V W ??? > { # z ^ /? 7VWo? CRVS3ӷ ޶ ? ڝ } Ϳ O=q ~ ? IY ?MvN Y k 7[ hwg < / O s7o u ? 3F 8 | ~ᗟ} v' #g 6 /| ~ᫍ( ?p( B _? sY G>| ŗ޸ V)% \\Z J 7/...........

I want it to show me watermarked image. How can I fix this?

You have the wrong set. Your HTML should look like:

<img src="image.php?src=images/ornek.jpeg" />

And image.php should be like this:

$stamp = imagecreatefromjpeg('images/wm.png');
$im = imagecreatefromjpeg($_GET['src']); 
$marge_right = 10;
$marge_bottom = 10;
$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));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

You can't put binary data in the src attribute of an image tag.

The src attribute expects usually an URL to an image.

You could do it with base64 encoding though:

$file = base64_encode(img_watermark('images/ornek.jpeg'));
echo "<img src='data:image/jpeg;base64,".$file."' alt='watermarked image'>";

and remove the header line in your function, unless your PHP file is supposed to send image data instead of HTML. Better not mix those things up :(

Set this as your header:

header("Content-type:image/jpeg");

instead of:

header("Content-type:image/png");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM