为上传的图片添加水印图片

add watermark image to uploaded image

我正在使用此代码将 png 图像添加为上传图像的水印,但结果不是图像并且不想使用 header() 我希望代码继续执行其他 php 查询无需导航到另一个页面来显示图像。图片已上传但没有水印并且 header() 没有 post 任何图片只是一个小的灰色方块

$path = "../large/";
$num = substr(md5(mt_rand(1,9999999999)),0,9);    
$new_name = $path.$num.".jpg";
$image = $num.".jpg";
move_uploaded_file($img_tmpname,$new_name);
$image = imagecreatefromjpeg($new_name);
$logoImage = imagecreatefrompng("images/watermark.png");
imagealphablending($logoImage, true);
$imageWidth=imagesx($image);
$imageHeight=imagesy($image); 
$logoWidth=imagesx($logoImage);
$logoHeight=imagesy($logoImage);

imagecopy(
  // destination
  $image,
  // source
  $logoImage,
  // destination x and y
  $imageWidth-$logoWidth, $imageHeight-$logoHeight,
  // source x and y
  0, 0,
  // width and height of the area of the source to copy
  $logoWidth, $logoHeight);

// Set type of image and send the output
header("Content-type: image/png");
imagePng($image);

// Release memory
imageDestroy($image);
imageDestroy($imageLogo);

我使用下面的代码对此进行了测试,一切正常。显然,我使用了与我的测试系统相关的路径,但希望它能有所帮助。

上传和处理上传文件时最重要且经常被遗忘的事情之一是表格的 enctype - 所以我以我的测试表格为例。

如果要保存图像并显示带有水印的图像,请使用 imagepng 函数两次,一次带文件名,另一次不带。

<form method='post' action='/test/so/wtrmarkimg.php' enctype='multipart/form-data'>
    <h1>Image uploader - Watermark</h1>
    <input type='file' name='image' />
    <input type='submit' value='Submit' />
</form>

<?php

    #$path = "../large/";

    $path='c:/temp/';/* output path for images generated */
    $watermarksrc=realpath( 'c:/wwwroot/images/watermark.png' );    

    if( isset( $_FILES['image'] ) ){

        $img_tmpname=$_FILES['image']['tmp_name'];


        $num = substr( md5( mt_rand( 1,9999999999 ) ),0,9);    
        $new_name = $path.$num.".jpg";
        $image = $num.".jpg";

        if( move_uploaded_file( $img_tmpname, $new_name ) ){

            $image = imagecreatefromjpeg( $new_name );
            $logoImage = imagecreatefrompng( $watermarksrc );
            imagealphablending( $logoImage, true );

            $imageWidth=imagesx($image);
            $imageHeight=imagesy($image); 
            $logoWidth=imagesx($logoImage);
            $logoHeight=imagesy($logoImage);

            imagecopy(
              $image,
              $logoImage,
              $imageWidth-$logoWidth, $imageHeight-$logoHeight,
              0, 0,
              $logoWidth, $logoHeight );

            // Set type of image and send the output
            header("Content-type: image/png");
            imagepng( $image );/*display image with watermark */
            @imagepng( $image, $new_name );/* save image with watermark */

            // Release memory
            imagedestroy( $image );
            imagedestroy( $imageLogo );
        }
    } else {
        echo "ERROR";
        print_r($_FILES);   
    }
?>